W3docs

Java static Keyword

Declare class-level members in Java with static — static fields, methods, blocks, and nested classes.

static is the keyword that promotes a class member from "one per instance" to "one per class." A static field has a single copy shared by every object. A static method belongs to the class itself and runs without any instance. A static block runs once, when the class is first loaded. A static nested class lives inside another class without needing an enclosing object.

The single rule of thumb: static members do not have a this. Everything else about how they behave follows from that.

Static fields

A static field is declared with static in the class body. There's exactly one copy, regardless of how many instances exist:

public class Counter {
  static int total;       // one Counter.total for everybody
  int count;              // each Counter has its own count
}

Counter a = new Counter();   a.count++;   Counter.total++;
Counter b = new Counter();   b.count++;   Counter.total++;

System.out.println(a.count);          // 1
System.out.println(b.count);          // 1
System.out.println(Counter.total);    // 2

Reach a static field through the class name (Counter.total) — that's the canonical form. Java also lets you write a.total because a is a Counter, but every linter on Earth flags that style.

Static methods

A static method belongs to the class. Call it with ClassName.method(...):

public class MathUtil {
  public static int square(int n) {
    return n * n;
  }
}

int x = MathUtil.square(7);     // 49

Inside a static method, there is no this — you cannot read instance fields or call instance methods unqualified, because there's no current instance to read them from:

public class Counter {
  int count;
  static void reset() {
    count = 0;      // ERROR: cannot reference instance field from static context
  }
}

You can still take an instance as a parameter and operate on it:

static void resetThis(Counter c) {
  c.count = 0;     // ok — c is a parameter, not this
}

The reverse direction works fine: an instance method can call a static method without any ceremony, because the class is always around even when an instance exists.

When to choose static

The single test is whether the member depends on per-instance state.

Depends on this?Use
No — pure calculation, shared counter, factory methodstatic
Yes — reads or writes the object's own fieldsinstance
public static int hoursToSeconds(int h) { return h * 3600; }   // no this needed → static
public        int rentalDays()           { return days; }       // reads this.days → instance

A common smell: an instance method that ignores this. It's lying about being instance-specific — make it static and the caller no longer has to invent an object just to use it.

Static constants

The combination static final is the standard form for constants:

public static final double TAX_RATE = 0.08;
public static final int    MAX_RETRIES = 3;
public static final String DEFAULT_LOCALE = "en";

By convention, constants are named UPPER_SNAKE_CASE. They're inlined at compile time when the value is primitive or a String literal, which makes them as fast as a literal in the call site.

Static blocks

A static { ... } block runs once, when the class is first loaded into the JVM. Use it for one-time setup of static fields that need more than a single expression:

public class Lookup {
  static final Map<String, Integer> WEEKDAYS = new HashMap<>();
  static {
    WEEKDAYS.put("Mon", 1);
    WEEKDAYS.put("Tue", 2);
    WEEKDAYS.put("Wed", 3);
    WEEKDAYS.put("Thu", 4);
    WEEKDAYS.put("Fri", 5);
    WEEKDAYS.put("Sat", 6);
    WEEKDAYS.put("Sun", 7);
  }
}

Static blocks are powerful but easy to overuse. Prefer a simple field initializer when one expression suffices.

Static fields and static blocks run top to bottom in the order they appear in the source. If an initializer reaches a field (through a method) before that field's own line has run, it sees the default value (0, false, or null) — so order matters:

public class Order {
  static int a = compute();          // runs first; b is still 0 → a becomes 1
  static int b = 10;                 // runs second
  static int compute() { return b + 1; }
}
// Order.a == 1, Order.b == 10

(Reading b directly on that first line — static int a = b + 1; — is instead an "illegal forward reference" compile error; only the indirect path through a method exposes the default.)

Static nested classes

A class declared static inside another class is a static nested class. Unlike a non-static inner class, it doesn't carry an implicit reference to an instance of the outer class:

public class Outer {
  static class Inner {           // does not need an Outer instance
    void hello() { System.out.println("hi"); }
  }
}

Outer.Inner i = new Outer.Inner();   // create directly
i.hello();

This is how we've been wrapping helper classes in the same file as main in earlier static class Foo {...} blocks — main is static, so we need the helper to be static too in order to instantiate it without an enclosing Outer instance. The nested classes chapter covers all four flavors.

Static is not "the constructor"

Newcomers sometimes mix up "static = runs once" with "static = runs at object creation." Static initialization happens once per class, not once per object. The constructor runs once per object. They're distinct mechanisms and they fire in different situations.

Static members in interfaces

Interfaces can have static methods too. They behave the same as class statics — call them with InterfaceName.method(...):

public interface Path {
  static Path of(String s) { return new SimplePath(s); }
}

Path p = Path.of("/tmp/foo");

The interfaces chapter covers when this is a good idea (factory methods on the interface itself).

A worked example

java— editable, runs on the server

This program prints:

#1  apple   base=0.50 USD,  with tax=0.54
#2  bread   base=2.40 USD,  with tax=2.59
#3  butter  base=3.10 USD,  with tax=3.35
Total items ever created: 3

Notice how the example mixes all four flavors: the constants and the lookup table are filled before any Item exists, each Item keeps its own name and basePrice, and the single shared itemsCreated field hands out the running id.

What's next

static lets you say who owns a member. The next companion is final, which lets you say whether it can change. Together, static final is the standard form for constants; on its own, final shapes inheritance and immutable design. Continue to java-final.

Practice

Practice
Why does a static method get a compile error if it tries to read an instance field by its bare name?
Why does a static method get a compile error if it tries to read an instance field by its bare name?
Was this page helpful?