Static Members

An instance member belongs to each object. A static member belongs once to the class itself.

Named constants, factory methods, and stateless utilities are common static uses. Data that differs per object should remain an instance field.

Call behavior on the class

class Distance {
    static final int METERS_PER_KM = 1000;

    static int toMeters(int kilometers) {
        return kilometers * METERS_PER_KM;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Distance.toMeters(3));
        System.out.println(Distance.METERS_PER_KM);
    }
}

Output:

3000
1000

Both members belong to Distance rather than to a particular object, so they are accessed through the class name. No Distance object is needed.

Mutable static state is global state. It complicates tests and concurrent code, so keep it narrow and intentional.

Count how many Student objects are created.