A static variable in Java is a variable that is declared with the static keyword within a class. It is also known as a class variable. Here are the key characteristics and features of static variables:
Key Characteristics
Shared Across All Instances: A static variable is shared among all instances (objects) of the class. This means that if one instance modifies the value of a static variable, the change is reflected across all instances.
Memory Allocation: Static variables are allocated memory only once when the class is loaded, rather than each time an instance of the class is created. This can save memory when you need a variable that should be the same for all instances.
Accessed via Class Name: Static variables can be accessed directly using the class name, which makes it clear that they belong to the class itself, not to any particular instance. For example, ClassName.variableName.
Initialization: Static variables can be initialized when declared or in a static block.
Lifetime: The lifetime of a static variable is tied to the class itself. It exists as long as the class is loaded in memory.
Example
Here’s a simple example of a static variable:
class Counter {
static int count = 0; // Static variableCounter() {
count++; // Increment the static variable each time a new object is created
}static void displayCount() {
System.out.println("Count: " + count); // Accessing static variable
}
}public class Main {
public static void main(String[] args) {
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter.displayCount(); // Output: Count: 2
}
}
Static variables are used when you need a variable that is common to all instances of a class, such as a counter for the number of objects created. They provide a way to maintain shared state or data that is not tied to any individual object.