00:00

static Keyword in Java – Variables, Methods, Blocks and Classes

The static keyword makes a member belong to the class itself rather than to individual objects. A static variable has one shared copy for the whole class, a static method can be called without creating an object, and a static block runs once when the class is loaded.

This tutorial covers static variables, methods, blocks and nested classes, static imports, how static members are stored, and the rules and pitfalls of using static.

1. What static Means

Static variable shared by all objects of a class
Can be staticEffect
Variables (fields)One copy shared by all objects of the class
MethodsCalled on the class; no object needed; no access to this
BlocksRun once, when the class is initialised
Nested classesDo not need an instance of the outer class
ImportsUse static members without the class name

Local variables and top-level classes cannot be static.

2. Static Variables

A static variable is shared by every object of the class. Here a counter of issued tickets is shared, while each ticket keeps its own number:

StaticVariable.java
public class StaticVariable {
    static class Ticket {
        static int issued = 0;                  // one copy shared by all Ticket objects
        static final String EVENT = "Tech Fest 2026";
        final int number;                       // one copy per object

        Ticket() {
            issued++;
            number = issued;
        }
    }

    public static void main(String[] args) {
        Ticket t1 = new Ticket();
        Ticket t2 = new Ticket();
        Ticket t3 = new Ticket();
        System.out.println("t1=" + t1.number + ", t2=" + t2.number + ", t3=" + t3.number);
        System.out.println("Tickets issued for " + Ticket.EVENT + ": " + Ticket.issued);
    }
}
Output
t1=1, t2=2, t3=3
Tickets issued for Tech Fest 2026: 3
  • Access static variables through the class name: Ticket.issued. Using an object reference also works but is misleading.
  • static final fields are constants, like Math.PI.
  • Mutable static variables are global state: they are shared by all threads and all code, so use them sparingly.

3. Static Methods

Static methods are ideal for utilities and calculations that do not depend on an object's state, like Math.max() or Integer.parseInt():

StaticMethod.java
public class StaticMethod {
    static class Converter {
        private Converter() { }                                 // utility class: no instances

        static double celsiusToFahrenheit(double c) { return c * 9 / 5 + 32; }
        static double kmToMiles(double km) { return km * 0.621371; }
    }

    private int instanceCounter = 0;

    static void staticHelper() {
        // instanceCounter++;          // compile error: non-static field from a static context
        System.out.println("static methods are called on the class");
    }

    public static void main(String[] args) {
        System.out.println("30 C = " + Converter.celsiusToFahrenheit(30) + " F");
        System.out.printf("10 km = %.2f miles%n", Converter.kmToMiles(10));
        staticHelper();

        StaticMethod obj = new StaticMethod();       // instance members need an object
        obj.instanceCounter++;
        System.out.println("instanceCounter = " + obj.instanceCounter);
    }
}
Output
30 C = 86.0 F
10 km = 6.21 miles
static methods are called on the class
instanceCounter = 1
  • A static method cannot use instance fields or call instance methods directly, and cannot use this or super.
  • Static methods are not overridden; a subclass method with the same signature hides the parent's.
  • main is static so the JVM can call it without creating an object.

4. Static Blocks

A static initializer block runs once, when the class is first loaded and initialised, before main or any other use. It is useful for complex initialisation of static fields:

StaticBlock.java
import java.util.Map;
import java.util.HashMap;

public class StaticBlock {
    static final Map<String, Integer> COUNTRY_CODES;

    static {                                        // runs once, when the class is first used
        System.out.println("static block: loading country codes");
        Map<String, Integer> m = new HashMap<>();
        m.put("IN", 91);
        m.put("US", 1);
        m.put("JP", 81);
        COUNTRY_CODES = Map.copyOf(m);
    }

    public static void main(String[] args) {
        System.out.println("main starts");
        System.out.println("India: +" + COUNTRY_CODES.get("IN"));
        System.out.println("Japan: +" + COUNTRY_CODES.get("JP"));
    }
}
Output
static block: loading country codes
main starts
India: +91
Japan: +81

If a static block throws an exception, the class fails to initialise with ExceptionInInitializerError, so keep them simple.

5. Static Nested Classes and Static Imports

StaticNestedAndImport.java
import static java.lang.Math.max;
import static java.lang.Math.PI;

public class StaticNestedAndImport {
    // A static nested class does not need an instance of the outer class
    static class Point {
        final int x, y;
        Point(int x, int y) { this.x = x; this.y = y; }
        static Point origin() { return new Point(0, 0); }    // static factory method
        @Override public String toString() { return "(" + x + ", " + y + ")"; }
    }

    public static void main(String[] args) {
        Point p = new StaticNestedAndImport.Point(3, 4);
        System.out.println(p + " and origin " + Point.origin());

        // static import: use Math.max and Math.PI without the class name
        System.out.println("max(7, 12) = " + max(7, 12));
        System.out.printf("PI = %.4f%n", PI);
    }
}
Output
(3, 4) and origin (0, 0)
max(7, 12) = 12
PI = 3.1416
  • A static nested class is like a normal class placed inside another for organisation; it does not hold a reference to an outer object.
  • Static imports let you write max(7, 12) instead of Math.max(7, 12). Use them sparingly to keep code clear.

6. How Static Members Are Stored

Static fields belong to the class's runtime data, created when the class is initialised and kept as long as the class is loaded, usually for the whole life of the program. Instance fields live inside each object on the heap and disappear when the object is garbage-collected. Holding large objects in static fields can therefore cause memory leaks.

7. Static vs Instance Members

AspectStaticInstance
Belongs toThe classEach object
CopiesOneOne per object
Accessed viaClassName.memberobject.member
Can use thisNoYes
LifetimeWhile the class is loadedWhile the object is reachable
OverridingNot possible (hiding only)Possible

8. When to Use static

  • Constants: static final values.
  • Utility methods that only use their parameters.
  • Factory methods such as List.of() and LocalDate.now().
  • Counters or caches shared across objects (thread-safely).
  • Nested helper classes that do not need the outer object.

Avoid static when behaviour depends on object state, when you need polymorphism, or when global state would make testing hard.

9. Summary

  • static members belong to the class, not to objects.
  • Static variables are shared; static methods need no object and cannot use this.
  • Static blocks run once when the class is initialised.
  • Static nested classes need no outer instance; static imports shorten references.
  • Use static for constants, utilities and factories; avoid mutable global state.

Related Tutorials