static members belong to the class, not to any object: one copy, shared by all instances, usable without new.
Where static can appear
| On | Meaning | Typical use |
|---|---|---|
| Field | One copy per class (in the class's data, not in each object) | Counters, constants (static final), caches |
| Method | Called on the class; no this | Utilities (Math.max), factories (List.of) |
Block static { } | Runs once when the class is initialised | Complex static setup |
| Nested class | A class inside a class that needs no outer instance | Builders, helper types, Map.Entry |
| Import | import static java.lang.Math.*; | Use sqrt(x) without the class name |
Static field vs instance field
public class Main {
public static void main(String[] args) {
User a = new User("asha");
User b = new User("ravi");
User c = new User("meera");
System.out.println(a.id + " " + b.id + " " + c.id);
System.out.println("users created: " + User.created);
System.out.println(User.isValidName("x")); // static method: no object needed
}
}
class User {
static int created = 0; // shared by all Users
final int id; // each User has its own
final String name;
User(String name) {
this.name = name;
this.id = ++created;
}
static boolean isValidName(String s) {
// return name.length() > 1; // would not compile: no 'this' in a static method
return s.length() > 1;
}
}1 2 3
users created: 3
falseWhat a static method can and cannot touch
Static blocks and lazy initialisation
import java.util.Map;
public class Main {
public static void main(String[] args) {
System.out.println("main starts");
System.out.println(Codes.lookup("IN"));
System.out.println(Codes.lookup("JP"));
}
}
class Codes {
private static final Map<String, String> NAMES;
static {
System.out.println("Codes initialised"); // runs on first use, once
NAMES = Map.of("IN", "India", "JP", "Japan");
}
static String lookup(String code) { return NAMES.get(code); }
}main starts
Codes initialised
India
JapanWhy is main static?
The JVM must call main before any object of your class exists. Making it static lets the launcher invoke Main.main(args) directly on the class without having to choose a constructor.
Static nested class
public class Main {
public static void main(String[] args) {
Order.Line line = new Order.Line("pen", 3); // no Order instance needed
System.out.println(line.item() + " x" + line.qty());
}
}
class Order {
record Line(String item, int qty) { } // nested records/enums/interfaces are implicitly static
}pen x3Can we override a static method?
Can a static method access instance variables?
When is a static block executed?