static (keyword)
static marks a field or method as belonging to the class itself, not to any particular instance. A static field has one copy shared by all instances; a static method is called on the class without needing an object.
Static field
public class Counter {
public static int total = 0; // one copy, shared
public int id; // each instance has its own
public Counter() {
total++;
this.id = total;
}
}
new Counter(); new Counter();
System.out.println(Counter.total); // 2
Static method
public class MathUtils {
public static double square(double x) { return x * x; }
}
double sq = MathUtils.square(5); // no object created
Static methods cannot use this (no instance context) and cannot directly access instance fields.
Static constants
public static final int MAX_RETRIES = 3;
public static final String DEFAULT_ENCODING = "UTF-8";
Static initializer block
public class DbPool {
private static final Connection conn;
static {
conn = DriverManager.getConnection("jdbc:...");
}
}
main is static
public static void main(String[] args) must be static — the JVM calls it before creating any instance of your class. Instance methods on main would have no object to run on.
See the full static guide for nested static classes and common gotchas.