Junior — Middle
Can you explain the meaning and usage of the static keyword in Java?
sobes.tech AI
Answer from AI
In Java, the keyword static is used to indicate that a field, method, or nested class belongs to the class itself rather than to any specific instance of the class. This means that static members exist in a single copy and are accessible without creating an object.
Application of static:
- Static fields (variables) — shared among all instances of the class, for example, a counter for created objects.
- Static methods — can be called without creating an object, for example,
Math.sqrt(). - Static blocks and nested classes — used for initialization and code organization.
Example:
public class Counter {
private static int count = 0; // shared among all objects
public Counter() {
count++;
}
public static int getCount() {
return count;
}
}
// Usage:
System.out.println(Counter.getCount()); // call without creating an object
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // 2