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 static field exists once per class. In HotSpot, static fields are stored with the class's java.lang.Class object, so they live as long as the class is loaded, which for classes on the application class path means the whole run. Strictly speaking it is once per class per class loader: two loaders that load the same class each have their own copy, as the class loading page shows.

A static method has no this. It can use static fields and its parameters, but not instance fields, and it is chosen at compile time from the declared type, not dispatched at run time like instance methods. Static code runs when the class is initialized, which happens once, on first active use: creating an instance, calling a static method, or reading or writing a static field that is not a compile-time constant.

Where static can appear
UseSinceMeaningBest for
Static fieldJava 1.0One variable shared by all instancesCounters, caches, configuration (with care)
static final constantJava 1.0Primitive or String with a constant value is inlined into callersTrue constants that never change
Static methodJava 1.0A method without this, bound at compile timeUtility functions, factory methods
Static initializer blockJava 1.0Code run once when the class is initializedBuilding complex static state
Static nested classJava 1.1A class inside another, without a link to an outer objectHelpers, builders, map entries
import staticJava 5Use static members without the class nameConstants and test assertions
Static methods in interfacesJava 8Static helpers declared in the interface itselfComparator.comparing, List.of
Static members of inner classesJava 16 (JEP 395)Inner classes may now declare static membersCounters 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.

Java
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:

Output
a.serial = 1, b.serial = 2
3 objects created
through a null reference: 3
  • created exists once, so each constructor saw the value left by the previous one: serials 1, 2 and 3, and describe() reported 3 objects. serial is an instance field, a separate copy in each object.
  • describe() is static and therefore cannot read serial: 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".
  • Reading ref.created through a null reference did not throw. The compiler replaced it with StaticMembers.created, ignoring the reference entirely. Accessing static members through instances is legal but misleading, which is why javac -Xlint:static warns about it; the method suppresses that warning on purpose.
  • 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().

Java
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:

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 new Derived(): 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.
  • Then the object was built: Base's instance fields and constructor (5 and 6), and only then Derived's instance fields, instance initializer block and constructor body (7 to 9). The super() call, written or implied, runs before any of the subclass's own field initializers.
  • 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 ExceptionInInitializerError and every later use NoClassDefFoundError, as shown on the class loading page.

Constants are copied into the classes that use them

A static final field of a primitive type or String, initialized with a constant expression, is a compile-time constant, and javac copies its value into every class that uses it. The program compiles a small library and an application against it, then replaces the library with a version that changes every value from 10 to 20, without recompiling the application.

Java
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:

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, LIMIT still printed 10: the application's class file contains the literal 10, and reading Lib.LIMIT does not even load Lib. 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".
  • BOXED_LIMIT is an Integer, which is not a constant type, and limit() is a method, so both were read at run time and showed 20.
  • Use static final 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 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.

Java
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:

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 Helper has only its own field. The inner Child, which uses bigState, has a hidden field this$0 pointing to its outer object. Through it, one small Child 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.
  • Quiet, an inner class that never touches its outer object, has no this$0: recent versions of javac omit the field when it is not needed (JDK-8271623). An instance of it still cannot be created without an outer object, though.
  • The inner class declared a static field, created. Before Java 16 that was a compile error; JEP 395, which finalized records, also relaxed this rule.
  • Rule of thumb: make nested classes static unless they really need the outer instance. See inner 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.

Java
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:

Output
shared cache: [from main]
static call via Parent-typed variable: parent
Order.INSTANCE.seen = 0, Order.counter = 10
  • The static final 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.
  • Child.who() does not override Parent.who(); it hides it. Called through a variable declared as Parent, the result was "parent" although the object is a Child, because static calls are bound to the declared type at compile time. Adding @Override to a static method is a compile error, which is a quick way to find out.
  • Order.INSTANCE was created while the class was being initialized, before the line counter = 10 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.

When to use static

static guidelines
SituationRecommendation
A function that needs no object stateA static method, often in a final utility class with a private constructor
Creating objects with a descriptive nameA static factory method, such as of or from
A true, never-changing constantstatic final in upper case
A value that may change between releasesA method or a non-constant field, so callers are not inlined
A helper class used only by its outer classA private static nested class
Shared mutable stateAvoid; if unavoidable, make it thread-safe and resettable
Polymorphic behaviourInstance methods, never static ones
Lazy, thread-safe single instanceA holder class or an enum; see design patterns

Static imports deserve the same restraint: import static org.junit.jupiter.api.Assertions.*; reads well in a test, but importing many static members into ordinary code hides where each name comes from, and two imports with the same member name make every use ambiguous. Related pages: final, access modifiers and inheritance and polymorphism.