+91 81900 98289

Java Static

A static field belongs to the class, not to one object. Every object sees the same static value. Use it for a shared counter or a constant. A static method can be called on the class name: Math.max(2, 9).

Static methods cannot read instance fields directly, because there is no particular object in scope. If the data belongs to one student, keep the method non-static.

Example

Each constructor adds 1 to the shared field. Two objects mean the field ends at 2.

public class Counter { static int created = 0; Counter() { created = created + 1; } public static void main(String[] args) { new Counter(); new Counter(); System.out.println(Counter.created); } }
Math is a class of static helpers. You do not write new Math(). You call Math.sqrt or Math.max on the class.