Junior — Middle
What is the purpose of the static modifier in Java and in what scenarios is it used?
sobes.tech AI
Answer from AI
In Java language, the static modifier is used to indicate that a class member (variable or method) belongs to the class itself rather than to a specific instance.
Main features and usage scenarios:
-
Static variables (fields) — shared among all objects of the class. For example, a counter of created objects.
-
Static methods — can be called without creating an instance of the class. Usually used for utility or factory methods.
-
Static initialization blocks — executed when the class is loaded, used for complex initialization of static fields.
Example:
public class Counter {
private static int count = 0; // shared variable for all objects
public Counter() {
count++;
}
public static int getCount() {
return count;
}
}
// Usage:
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // Outputs 2
Thus, static allows creating members that do not depend on a specific object, which is convenient for storing common data or creating utility methods.