Static Variable
In Java, a static variable is a class-level variable that belongs to the class itself rather than to instances (objects) of the class. This means that all instances of the class share the same copy of the static variable. Static variables are declared using the static
keyword.
Here are some key points about static variables:
Class-Level Scope: Static variables are associated with the class itself rather than with individual instances of the class. They are stored in memory once per class, regardless of how many instances of the class are created.
Shared among Instances: Since static variables belong to the class, they are shared among all instances of the class. Any changes made to a static variable by one instance will be reflected in all other instances of the class.
Initialization: Static variables can be initialized when they are declared, or they can be initialized later in a static initialization block or a static method.
Accessing Static Variables: Static variables can be accessed using either the class name followed by the dot operator (ClassName.staticVariable
) or directly within static methods or constructors of the class.
Visibility: Static variables can have different access modifiers (e.g., public
, private
, protected
, or default package-private). The choice of access modifier determines the visibility of the static variable to other classes.
Lifecycle: Static variables are initialized when the class is loaded into memory and exist for the duration of the program's execution. They are typically used to store class-level data or configuration settings that are common to all instances of the class.
Common Use Cases: Static variables are commonly used to represent constants, maintain global state, or share data across instances of the class. They are also used in utility classes and singleton patterns.
Here's an example demonstrating the use of a static variable in Java:
public class MyClass {
// Static variable
public static int count;
public MyClass() {
// Incrementing the static variable in the constructor
count++;
}
public static void main(String[] args) {
// Creating multiple instances of MyClass
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();
// Accessing the static variable using the class name
System.out.println("Total count: " + MyClass.count); // Output: Total count: 3
}
}
In the example above, the count
static variable is incremented each time a new instance of MyClass
is created. Since count
is a static variable, its value is shared among all instances of the class. Therefore, the output of the program is Total count: 3
, indicating that three instances of MyClass
have been created.
Thank you,