Junior — Middle
How does a static variable in programming differ, and what are its features?
sobes.tech AI
Answer from AI
A static variable is a variable that belongs to the class rather than a specific instance of an object. It exists as a single instance for the entire class and retains its value between method calls.
Features of static variables:
- Shared among all instances of the class: all objects of the class share the same static variable.
- Initialized once when the class is loaded.
- Accessible without creating an instance of the class (through the class name).
- Used to store state or data common to all objects.
Example in Java:
public class Counter {
public static int count = 0;
public Counter() {
count++;
}
}
// Usage:
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.count); // Will output 2
In testing, static variables can create difficulties because their state persists between tests, which can lead to undesirable side effects. Therefore, it is important to clear or isolate static data in tests.