Sobes.tech
Junior — Middle

Explain what the keyword static means in Java and how it is used.

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.

Main uses of static:

  • Static fields (class variables) — shared among all instances of the class. For example, a counter for created objects.
  • Static methods — can be called without creating an object, and only work with other static members.
  • Static blocks and nested classes — 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());
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // Will print 2