The static keyword
static makes a field, method, block or nested class belong to the class itself instead of to each object. That sounds simple, but it decides when code runs, what the compiler copies into other classes, and which objects stay in memory. This page explains where static members live, then shows shared state, the exact initialization order with inheritance, compile-time constants that survive a library upgrade, nested versus inner classes, and the hiding and ordering traps.
Contents
What static means
An instance field exists once per object; a staticjava.lang.Class
A staticthis
| Use | Since | Meaning | Best for |
|---|---|---|---|
| Static field | Java 1.0 | One variable shared by all instances | Counters, caches, configuration (with care) |
static final | Java 1.0 | Primitive or String | True constants that never change |
| Static method | Java 1.0 | A method without this | Utility functions, factory methods |
| Static initializer block | Java 1.0 | Code run once when the class is initialized | Building complex static state |
| Static nested class | Java 1.1 | A class inside another, without a link to an outer object | Helpers, builders, map entries |
import static | Java 5 | Use static members without the class name | Constants and test assertions |
| Static methods in interfaces | Java 8 | Static helpers declared in the interface itself | Comparator.comparingList.of |
| Static members of inner classes | Java 16 (JEP 395) | Inner classes may now declare static members | Counters or constants inside an inner class |
The examples ran on JDK 21.
Shared fields and static methods
Three objects are created; each takes the next serial number from a shared counter. The last call reads the static field through a variable that holds null
public class StaticMembers {
static int created; // one copy shared by all instances
final int serial; // one copy per instance
StaticMembers() {
created++;
serial = created;
}
static String describe() { // no 'this': cannot read serial here
return created + " objects created";
}
public static void main(String[] args) {
StaticMembers a = new StaticMembers();
StaticMembers b = new StaticMembers();
new StaticMembers();
System.out.println("a.serial = " + a.serial + ", b.serial = " + b.serial);
System.out.println(StaticMembers.describe());
// Static members belong to the class; calling through a reference is misleading
StaticMembers nothing = null;
System.out.println("through a null reference: " + accessStatic(nothing));
}
@SuppressWarnings("static")
static int accessStatic(StaticMembers ref) {
return ref.created; // compiles to StaticMembers.created: no NPE
}
}
Output:
a.serial = 1, b.serial = 2
3 objects created
through a null reference: 3
exists once, so each constructor saw the value left by the previous one: serials 1, 2 and 3, andcreated reported 3 objects.describe() is an instance field, a separate copy in each object.serial is static and therefore cannot readdescribe() : there is no object whose serial it would be. The compiler rejects such access with "non-static variable cannot be referenced from a static context".serial- Reading
through aref.created reference did not throw. The compiler replaced it withnull , ignoring the reference entirely. Accessing static members through instances is legal but misleading, which is whyStaticMembers.created warns about it; the method suppresses that warning on purpose.javac -Xlint:static - A plain static counter like this is not thread-safe: two threads can read the same value and both store the same increment. Shared static state needs an
AtomicInteger or a lock.
Initialization order, with inheritance
Every static and instance initializer in a small class hierarchy prints a numbered line, so the output shows the exact order of the first and second new Derived()
public class InitOrder {
static int log(String s) {
System.out.println(s);
return 1;
}
static class Base {
static int baseStatic = log(" 1. Base static field");
static {
log(" 2. Base static block");
}
int baseField = log(" 5. Base instance field");
Base() {
log(" 6. Base constructor");
}
}
static class Derived extends Base {
static int derivedStatic = log(" 3. Derived static field");
static {
log(" 4. Derived static block");
}
int derivedField = log(" 7. Derived instance field");
{
log(" 8. Derived instance initializer block");
}
Derived() {
super(); // Base is fully built first
log(" 9. Derived constructor body");
}
}
public static void main(String[] args) {
System.out.println("main starts; neither class is initialized yet");
System.out.println("first new Derived():");
new Derived();
System.out.println("second new Derived(): static parts do not run again");
new Derived();
}
}
Output:
main starts; neither class is initialized yet
first new Derived():
1. Base static field
2. Base static block
3. Derived static field
4. Derived static block
5. Base instance field
6. Base constructor
7. Derived instance field
8. Derived instance initializer block
9. Derived constructor body
second new Derived(): static parts do not run again
5. Base instance field
6. Base constructor
7. Derived instance field
8. Derived instance initializer block
9. Derived constructor body
- Nothing ran before the first
: classes are initialized lazily. Then the superclass was initialized first (steps 1 and 2), then the subclass (3 and 4). Within a class, static field initializers and static blocks run top to bottom, in the order they appear in the source.new Derived() - Then the object was built:
's instance fields and constructor (5 and 6), and only thenBase 's instance fields, instance initializer block and constructor body (7 to 9). TheDerived call, written or implied, runs before any of the subclass's own field initializers.super() - The second object repeated steps 5 to 9 only. Static initialization happens once per class, and the JVM makes it thread-safe: if two threads use the class at the same time, one waits for the other to finish it.
- A static block that throws leaves the class unusable: the first use gets
and every later useExceptionInInitializerError , as shown on theNoClassDefFoundErrorclass loading page .
Constants are copied into the classes that use them
A static finalStringjavac
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.spi.ToolProvider;
public class ConstantInlining {
// Library version 1, and an application compiled against it
static final String LIB_V1 = """
public class Lib {
public static final int LIMIT = 10; // compile-time constant
public static final Integer BOXED_LIMIT = 10; // not a constant
public static int limit() { return 10; }
}""";
static final String APP = """
public class App {
public static String report() {
return "LIMIT=" + Lib.LIMIT + " BOXED_LIMIT=" + Lib.BOXED_LIMIT
+ " limit()=" + Lib.limit();
}
}""";
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("inline");
compile(dir, "Lib", LIB_V1);
compile(dir, "App", APP);
System.out.println("built with Lib v1: " + run(dir));
// Ship a new Lib with 20 everywhere, but do NOT recompile App
compile(dir, "Lib", LIB_V1.replace("10", "20"));
System.out.println("Lib v2, App not recompiled: " + run(dir));
}
static String run(Path dir) throws Exception {
try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()}, null)) {
return (String) loader.loadClass("App").getMethod("report").invoke(null);
}
}
static void compile(Path dir, String name, String source) throws Exception {
Path file = dir.resolve(name + ".java");
Files.writeString(file, source);
ToolProvider.findFirst("javac").orElseThrow().run(System.out, System.err,
"-cp", dir.toString(), "-d", dir.toString(), file.toString());
}
}
Output:
built with Lib v1: LIMIT=10 BOXED_LIMIT=10 limit()=10
Lib v2, App not recompiled: LIMIT=10 BOXED_LIMIT=20 limit()=20
- After the upgrade,
still printed 10: the application's class file contains the literal 10, and readingLIMIT does not even loadLib.LIMIT . This is binary compatibility as the JLS defines it (section 13.4.9), and a classic source of "the new library is deployed but nothing changed".Lib is anBOXED_LIMIT , which is not a constant type, andInteger is a method, so both were read at run time and showed 20.limit()- Use
constants for values that will truly never change, such as protocol numbers. For values that may change between releases, expose a method or a non-constant field, or always rebuild dependent code together.static final
Static nested classes versus inner classes
A class declared inside another is either a static nested class or an inner class. The difference is invisible in the source of the nested class but shows up in its fields. The outer class here holds 10 MB of state, to make the cost visible.
import java.lang.reflect.Field;
import java.util.Arrays;
public class NestedAndInner {
private final byte[] bigState = new byte[10000000]; // 10 MB per outer object
// A static nested class: never linked to a NestedAndInner object
static class Helper {
int value = 1;
}
// An inner class that uses its outer object
class Child {
int size() {
return bigState.length; // needs NestedAndInner.this
}
// Static members in inner classes are allowed since Java 16 (JEP 395)
static int created;
}
// An inner class that never touches its outer object
class Quiet {
int value = 3;
}
public static void main(String[] args) throws Exception {
System.out.println("Helper fields: " + names(Helper.class));
System.out.println("Child fields: " + names(Child.class));
System.out.println("Quiet fields: " + names(Quiet.class));
Child c = new NestedAndInner().new Child(); // the outer object stays reachable
Field outer = Child.class.getDeclaredField("this$0");
outer.setAccessible(true);
NestedAndInner owner = (NestedAndInner) outer.get(c);
System.out.println("a Child keeps " + owner.bigState.length / 1000000
+ " MB reachable through this$0 (size() = " + c.size() + ")");
Child.created++;
System.out.println("Child.created = " + Child.created);
}
static String names(Class<?> type) {
return Arrays.toString(Arrays.stream(type.getDeclaredFields())
.map(Field::getName).toArray());
}
}
Output:
Helper fields: [value]
Child fields: [created, this$0]
Quiet fields: [value]
a Child keeps 10 MB reachable through this$0 (size() = 10000000)
Child.created = 1
- The static
has only its own field. The innerHelper , which usesChild , has a hidden fieldbigState pointing to its outer object. Through it, one smallthis$0 kept the whole 10 MB outer object reachable. Inner class instances that outlive their outer object, for example stored in a cache or registered as listeners, are a common memory leak.Child , an inner class that never touches its outer object, has noQuiet : recent versions ofthis$0 omit the field when it is not needed (JDK-8271623). An instance of it still cannot be created without an outer object, though.javac- The inner class declared a static field,
. Before Java 16 that was a compile error; JEP 395, which finalized records, also relaxed this rule.created - Rule of thumb: make nested classes
unless they really need the outer instance. Seestaticinner classes for local and anonymous classes.
Static traps: global state, hiding and order
Three mistakes that static makes easy: mutable shared state, expecting static methods to be overridden, and a static field that is read before its initializer has run.
import java.util.ArrayList;
import java.util.List;
public class StaticPitfalls {
// A mutable static is global state shared by every caller and thread
static final List<String> CACHE = new ArrayList<>();
static class Parent {
static String who() {
return "parent";
}
}
static class Child extends Parent {
static String who() { // hides, does not override
return "child";
}
}
// Initialization order trap: static fields initialize top to bottom
static class Order {
static final Order INSTANCE = new Order();
static int counter = 10; // runs AFTER INSTANCE was constructed
final int seen;
Order() {
seen = counter; // counter is still 0 here
}
}
public static void main(String[] args) {
CACHE.add("from main");
System.out.println("shared cache: " + CACHE);
Parent p = new Child();
System.out.println("static call via Parent-typed variable: " + callWho(p));
System.out.println("Order.INSTANCE.seen = " + Order.INSTANCE.seen
+ ", Order.counter = " + Order.counter);
}
@SuppressWarnings("static")
static String callWho(Parent p) {
return p.who(); // resolved from the declared type: Parent
}
}
Output:
shared cache: [from main]
static call via Parent-typed variable: parent
Order.INSTANCE.seen = 0, Order.counter = 10
- The
list is final only as a reference; anyone can add to it. A mutable static is global state: shared by every caller and thread, kept for the whole run, and hard to reset between tests. Prefer passing objects to the code that needs them.static final does not overrideChild.who() ; it hides it. Called through a variable declared asParent.who() , the result was "parent" although the object is aParent , because static calls are bound to the declared type at compile time. AddingChild to a static method is a compile error, which is a quick way to find out.@Override was created while the class was being initialized, before the lineOrder.INSTANCE had run, so the constructor saw the default value 0. Static initializers run strictly top to bottom; a static field that creates an instance of its own class must come after every static field the constructor uses.counter = 10
When to use static
| Situation | Recommendation |
|---|---|
| A function that needs no object state | A static method, often in a final utility class with a private constructor |
| Creating objects with a descriptive name | A static factory method, such as offrom |
| A true, never-changing constant | static final |
| A value that may change between releases | A method or a non-constant field, so callers are not inlined |
| A helper class used only by its outer class | A private static |
| Shared mutable state | Avoid; if unavoidable, make it thread-safe and resettable |
| Polymorphic behaviour | Instance methods, never static ones |
| Lazy, thread-safe single instance | A holder class or an enum; see |
Static imports deserve the same restraint: import static org.junit.jupiter.api.Assertions.*;