Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 201 ยท Object-Oriented Programming

Static Fields, Methods and Blocks

Learn Java static members - shared fields and counters, static methods, utility classes, static and instance initializer blocks, and the exact initialization order.

Most of what you've put in classes so far belongs to each object: every Booking has its own guests and nights. Sometimes, though, a piece of data or behavior belongs to the class as a whole: a counter of how many objects were created, a constant like a maximum size, a helper method like Math.sqrt that needs no object at all. The static keyword marks those members.

A static field exists exactly once, no matter how many objects you create (even zero). A static method runs without any object, so it has no this. This lesson covers both, plus the two kinds of initializer blocks and the precise order in which Java sets up classes and objects, which is a favorite interview topic and the source of some genuinely confusing bugs.

Static fields: one copy per class

An instance field gets a fresh copy in every object. A static field lives in the class and is shared by all of its objects. The classic use is handing out unique IDs:

Java A static counter that numbers every object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Ticket.issued is read before any ticket exists, and it prints 0: static fields don't need objects. Each constructor call bumps the one shared counter, and each ticket copies the current value into its own number. Refer to static members through the class name (Ticket.issued), which tells readers at a glance that the value is shared.

Static fields get the same default values as instance fields (0, false, null) and are usually private like any other field. The big exception is constants.

Static constants

A field that is static final and holds an unchanging value is a constant. By convention its name is in UPPER_SNAKE_CASE:

Java
class Booking {
    static final int MAX_GUESTS = 6;
    static final String SUPPORT_EMAIL = "[email protected]";
    static final List<String> ROOM_TYPES = List.of("single", "double", "suite");
}

Constants are often public, because they can't be changed. Make sure the value really is immutable, though: a static final ArrayList can still be modified by anyone who can reach it. Constants and final covers the details.

Static methods

A static method belongs to the class and is called through the class name: Math.max(a, b), Integer.parseInt("42"), List.of(1, 2). Because there's no object, a static method has no this and can't use instance fields or instance methods directly. The rules in both directions:

From... can use static members? can use instance members?
an instance method yes yes (of this)
a static method yes only through an object reference
Java What static and instance methods can reach

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

warmer is static but still reads target, because it has explicit Thermostat references to read it from. What a static method can't do is use a bare target, because that would mean this.target, and there is no this. The compiler says non-static variable target cannot be referenced from a static context. You met this rule in The this Keyword, and it's why main usually creates an object before calling instance methods.

When should a method be static?

Make a method static when it doesn't depend on any object's state: conversions, calculations on its parameters, validation helpers, and static factory methods like Money.of(...) that create objects. If a method reads or changes fields of an object, it should be an instance method of that object's class. Static vs Instance Methods has more examples.

Avoid calling static members through an object reference. hall.clamp(50) compiles, but it suggests the result depends on hall when it doesn't. Static methods also aren't polymorphic: a subclass can declare a static method with the same signature, but that hides the parent's method instead of overriding it, and the call is chosen by the declared type at compile time (Polymorphism).

Utility classes

A class that only groups static helpers is called a utility class. java.lang.Math, java.util.Arrays, java.util.Collections and java.util.Objects are the JDK's best-known ones. Give your own a final modifier and a private constructor, so nobody creates pointless instances or subclasses it:

Java
final class Slugs {
    private Slugs() {}                               // no instances

    static String of(String title) {
        return title.strip().toLowerCase().replaceAll("[^a-z0-9]+", "-");
    }
}

Utility classes are fine for genuinely stateless helpers. If one starts to collect unrelated methods ("Utils", "Helpers"), or if its methods need configuration, it's usually a sign that the behavior belongs on an object instead.

Initializer blocks

Besides field initializers and constructors, a class can contain two kinds of anonymous code blocks:

  • A static initializer (static { ... }) runs once, when the class is initialized. Use it for setup that doesn't fit in one expression, such as filling a lookup table.
  • An instance initializer ({ ... }, no keyword) runs every time an object is created, before the constructor body. It's rare in practice; constructors and field initializers usually say the same thing more clearly.

The demo below prints a line from every step, so you can see the exact order:

Java The initialization order, step by step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows the rules:

  1. main starts prints first: a class is initialized lazily, at its first real use (here new Widget), not when the program starts.
  2. Static field initializers and static blocks run once, in the order they appear in the source.
  3. For each object: instance field initializers and instance blocks run in source order, then the constructor body. (Strictly, this happens right after the constructor's implicit super() call; the full picture with parent classes is in The super Keyword.)

Because static initializers run in textual order, a static field that reads another static field declared below it sees the default value, not the one you wrote. Keep dependent static fields in top-to-bottom order.

Lookup tables and the constant trap

A static block is the natural home for building a table once. Here's one that also shows a surprise: reading a compile-time constant doesn't initialize the class at all, because the compiler copies the constant's value directly into the calling code:

Java A static lookup table and lazy class initialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

(building the Morse table) appears only after now encoding.... Reading MAX_LENGTH, a static final primitive initialized with a constant expression, never touched the Morse class at run time. That matters in two situations: a static block with side effects (like the print here) may not run when you expect, and if you change such a constant in a library, code compiled against the old version keeps the old value until it's recompiled.

If a static initializer throws an exception, the JVM reports ExceptionInInitializerError, and every later use of that class fails with NoClassDefFoundError. Keep static blocks short and safe, and prefer lazy setup for anything that can fail, such as reading files.

Static state: use with care

A mutable static field is effectively a global variable: any code anywhere can change it, and every object sees the change. That causes problems that grow with the program:

  • Hidden coupling. A method's behavior depends on a value set somewhere else entirely.
  • Testing. Tests that run in the same JVM share static state, so one test can break another.
  • Threads. Shared mutable state needs synchronization. Even issued++ in the Ticket example isn't safe if two threads create tickets at once; an AtomicInteger would be (Atomic Variables).
  • Memory leaks. A static collection lives as long as its class, usually the whole program. Objects you add and forget are never garbage collected (Memory and Garbage Collection).

Good uses of static: constants, stateless helpers, factory methods, and carefully designed shared resources. For anything else, prefer passing objects to the code that needs them.

Other uses of static

  • Static nested classes are classes declared inside another class with static. They don't need an instance of the outer class (Nested, Inner, Local and Anonymous Classes).
  • Static imports let you write max(a, b) instead of Math.max(a, b): import static java.lang.Math.max; (Packages and Imports).
  • Interfaces can have static methods, such as List.of and Comparator.comparing (Interfaces).
  • The main method is traditionally public static void main(String[] args), so the JVM can call it without creating an object. Since Java 25, main can also be an instance method like void main(); the launcher then creates the object for you (The main Method and Command-Line Arguments).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class has static int created; and its constructor does created++. After new A(); new A(); new A();, what is A.created?

    A static field exists once per class. All three constructor calls increment the same counter.
  2. 2. Which line fails to compile inside static void reset() of a class with an instance field int level?

    A bare level means this.level, and static methods have no this. Declaring a local variable, calling static methods or using an explicit object reference are all fine.
  3. 3. In what order do these run for the first new Box()? (a) the constructor body, (b) a static block, (c) an instance initializer block

    Static initialization happens once, when the class is first used. Then, for each object, instance initializers run before the constructor body.
  4. 4. class Config { static final int PORT = 8080; static { IO.println("init"); } } โ€” what does IO.println(Config.PORT); print in a fresh program?

    The compiler inlines constant values like PORT into the calling code, so the Config class is never initialized and its static block doesn't run.
  5. 5. Which is the best reason to make a method static?

    Static methods suit work that depends only on parameters (or static state). They can't be overridden and have no this, so they can't change the current object.

Summary

  • static members belong to the class: a static field exists once, shared by all objects; a static method runs without an object and has no this.
  • Refer to static members through the class name; static code can use instance members only through an explicit object reference.
  • static final constants use UPPER_SNAKE_CASE; utility classes are final with a private constructor.
  • Static blocks run once, when the class is first used; instance blocks and field initializers run for every object, before the constructor body, all in source order.
  • Reading a compile-time constant doesn't initialize its class; a failing static initializer causes ExceptionInInitializerError.
  • Mutable static state is global state: it couples code, complicates tests and threads, and can leak memory.

Next: Inheritance, where one class builds on another with extends.