All topics
library
beginner

The static Keyword

Know every use of static in Java: fields, methods, blocks, nested classes, and imports.

static means "belongs to the class, not to an instance". It has five uses.

Static = a shared whiteboard in the office (one copy, everyone reads/writes the same board). Instance = personal notebooks (each person has their own).

Key Concepts

1
1. Fields — one copy, shared.
    class Counter {
      static int created;          // one, for all instances
      int id;                      // one per instance
      Counter() { id = ++created; }
    }
2
2. Methods — called on the class.
    Math.max(a, b);
    List.of(1, 2, 3);
3
A static method has no this, so it cannot read instance fields. That is why main is static: it runs before any object exists.
thismain
4
3. Blocks — run once, when the class loads.
    static final Map<String, Integer> CODES = new HashMap<>();
    static {
      CODES.put("OK", 200);
      CODES.put("NOT_FOUND", 404);
    }
5
Blocks run in declaration order and are for initialisation too complex for one expression.
6
4. Nested classes.
    class Outer {
      static class Node { }        // no reference to Outer
      class Inner { }              // holds a hidden Outer reference
    }
7
Prefer the static one. A non-static inner class keeps its enclosing instance alive, which is a common and quiet source of memory leaks.
8
5. Static imports.
    import static java.lang.Math.PI;     // then just PI
9
Useful for constants, and bad for readability once a reader cannot tell where a name came from.
10
Static methods are not polymorphic. A subclass declaring the same signature hides rather than overrides, and dispatch follows the reference type.
11
The cost worth knowing. Mutable static state is global state: shared between tests, hard to reason about under concurrency, and awkward to replace with a stub. static final constants are fine; a static cache you mutate rarely is.
static finalstatic
12
What the interviewer is probing.1. "Why is main static?" Probing: whether you can reason about it rather than recite. Stalls: "That is the rule." Moves up: it runs before any object exists, so the JVM needs a method it can call without constructing anything.
13
2. "Can a static method be overridden?" Probing: hiding versus overriding. Stalls: "Yes." Moves up: no — it is hidden, and dispatch follows the reference type, which is why @Override will not compile on one.
14
3. "What is wrong with mutable static state?" Probing: testability and concurrency. Stalls: "Nothing, it is convenient." Moves up: it is global state shared between tests and threads, hard to isolate and hard to stub; static final constants are fine, a mutable static cache rarely is.
15
4. "When does a static initializer block run?" Probing: class loading. Stalls: "At startup." Moves up: on first active use of the class, once, in declaration order — which is why a class with an expensive static block can surprise you on first touch.