A class variable in Java is a variable that is declared with the static keyword within a class. It is also known as a static variable. Here are some key characteristics and features of class variables:
Key Characteristics
Shared Across All Instances: Class variables are shared among all instances (objects) of the class. This means that if one instance changes the value of a class variable, that change is reflected across all instances.
Memory Allocation: Class variables are allocated memory only once when the class is loaded, which helps in saving memory.
Accessed via Class Name: Class variables can be accessed directly using the class name, without needing to create an instance of the class. For example, ClassName.variableName.
Initialization: Like instance variables, class variables can be initialized when declared or in a static block.
Lifetime: The lifetime of a class variable is tied to the class itself. It exists as long as the class is loaded into memory.
Example
Here’s an example of a class variable in Java:
class Counter {
static int count = 0; // Class variableCounter() {
count++; // Increment the class variable
}static void displayCount() {
System.out.println("Count: " + count); // Accessing class variable
}
}public class Main {
public static void main(String[] args) {
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter.displayCount(); // Output: Count: 2
}
}
Class variables (static variables) are used for attributes that are common to all instances of a class, providing a way to maintain shared state or count occurrences, like in the example above.