static (Java)

static means a field or method belongs to the class itself rather than to any individual object. You can use a static member without creating an object first.

Java

A static field is shared by all objects of the class — there's only one copy. A static method is called on the class name (like Math.max(2, 5)) and can't use instance fields directly.

The main method is static so the JVM can run it without first creating an object of your class.

Examples

Java

public class Counter {
    static int total = 0;

    Counter() {
        total++;
    }

    public static void main(String[] args) {
        new Counter();
        new Counter();
        System.out.println(Counter.total);
    }
}

Output:

2

Learn it in a lesson

See also

Back to the Dictionary