The static Keyword
Members marked static belong to the class itself, not to any one instance of it. There is exactly one copy of a static field, shared by every object of that class — as opposed to instance (non-static) fields, where every object gets its own independent copy.
Static fields: shared across all instances
A shared counter
class Widget {
static int totalCreated = 0; // one copy, shared by every Widget
int id; // one copy per instance
Widget() {
totalCreated++; // updates the single shared copy
id = totalCreated;
}
}
public class Main {
public static void main(String[] args) {
Widget a = new Widget();
Widget b = new Widget();
Widget c = new Widget();
System.out.println(a.id); // 1
System.out.println(b.id); // 2
System.out.println(c.id); // 3
// All three share the SAME totalCreated field
System.out.println(Widget.totalCreated); // 3
}
}Each Widget gets its own id, but there is only ever one totalCreated in existence — every constructor call increments the same shared counter.
Static methods: called without an instance
A static method belongs to the class, not to any object, so it can be called directly through the class name — ClassName.method() — with no new required.
Calling a static method
class MathUtils {
static int square(int n) {
return n * n;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtils.square(5); // no instance needed
System.out.println(result); // 25
}
}This is exactly how you've been calling methods like Math.sqrt(...) or Integer.parseInt(...) all along — they're static methods on the Math and Integer classes.
Static methods can't touch instance members directly
This does not compile
class Widget {
int id; // instance field — belongs to a specific object
static void printId() {
System.out.println(id); // error: cannot make a static reference
// to the non-static field 'id'
}
}To fix this, either make printId an instance method, or pass in a specific Widget instance as a parameter so the method has something concrete to read from.
Static initializer blocks
A static block runs once, the first time the class is loaded by the JVM — useful for one-time setup of static fields that needs more than a simple assignment.
A static initializer
class Config {
static final Map<String, String> DEFAULTS = new HashMap<>();
static {
DEFAULTS.put("timeout", "30");
DEFAULTS.put("retries", "3");
}
}Static fields belong to the class and are shared by every instance.
Static methods are called through the class name and need no instance.
Static methods cannot directly access instance fields or methods — there is no
this.A static initializer block runs once, when the class is first loaded.