The static Keyword in Java

static binds a member to the class rather than to any instance, which changes when it is created, how it is accessed and what it can see.

Definition

A static member belongs to the class, not to any object of it. There is exactly one copy, it exists as soon as the class is loaded, and it is reached through the class name.

Static fields

public class Registration {

    private static int nextNumber = 1;    // shared by every object
    private final int number;              // one per object

    public Registration() {
        this.number = nextNumber++;
    }

    public static int issued() {
        return nextNumber - 1;
    }
}
new Registration();
new Registration();
System.out.println(Registration.issued());   // 2

Every instance sees the same nextNumber, which is exactly what a shared counter needs.

Static methods

public final class Distance {

    private Distance() { }

    public static double kilometresToMiles(double km) {
        return km * 0.621371;
    }
}

double miles = Distance.kilometresToMiles(120);

A static method depends only on its arguments. It cannot use this, cannot read instance fields, and cannot call instance methods without an object.

public class Example {

    private int count = 5;

    public static void wrong() {
        // System.out.println(count);   // compile error: no instance exists
    }

    public static void right(Example example) {
        System.out.println(example.count);   // fine, an object was supplied
    }
}

Static blocks

public class Configuration {

    private static final Map<String, String> DEFAULTS;

    static {
        Map<String, String> values = new HashMap<>();
        values.put("theme", "light");
        values.put("pageSize", "20");
        DEFAULTS = Map.copyOf(values);
    }
}

A static block runs once, when the class is initialised, in source order with the static field initialisers. Use it only when a constant needs more than a single expression.

Static nested classes

public class Cache {

    private static class Entry {      // no reference to the enclosing instance
        final String key;
        final String value;

        Entry(String key, String value) {
            this.key = key;
            this.value = value;
        }
    }
}

A static nested class is simply a class scoped inside another. Unlike an inner class it holds no hidden reference to the outer object, which makes it lighter and avoids accidental memory retention.

Static compared with instance

Aspectstaticinstance
Belongs toThe classEach object
CopiesOneOne per object
CreatedOn class initialisationOn new
Accessed byClassName.memberobject.member
Can use thisNoYes
OverridableNo, only hiddenYes

Static methods are hidden, not overridden

class Parent {
    static String name() { return "Parent"; }
}

class Child extends Parent {
    static String name() { return "Child"; }
}

Parent p = new Child();
System.out.println(p.name());   // Parent - resolved from the declared type
Static dispatch uses the compile time type; instance dispatch uses the runtime object. This example is a favourite in interviews because it looks like polymorphism and is not.

Constants

public static final int MAX_UPLOAD_MB = 25;
public static final List<String> ROLES = List.of("admin", "editor");

static final is the idiom for a constant. Note that final only stops reassignment, so a static final mutable collection is still a shared mutable variable. Use an immutable factory such as List.of.

Common mistakes

  • Reading an instance field from a static method and not understanding the error.
  • Using static state for application data, which turns into a hidden global and breaks under concurrency and in tests.
  • Expecting static methods to be polymorphic.
  • Calling a static method through an instance reference, which compiles but misleads the reader.
  • Declaring static final on a mutable object and treating it as immutable.

Best practices

  • Make a method static only when it uses no instance state.
  • Keep static mutable state out of application code; static should mean constant or stateless.
  • Always call static members through the class name.
  • Prefer a static nested class over an inner class unless the enclosing instance is genuinely needed.
  • Combine static final with genuinely immutable values.

Practice

  1. Write a class that counts how many objects of it have been created, and explain which field must be static.
  2. Why does calling an instance method from main without an object fail to compile?
  3. Predict the output of the Parent and Child example, then make name() non static and predict again.
  4. Explain the risk in public static final List<String> ROLES = new ArrayList<>();
  5. Convert a utility class full of instance methods into a static one and describe what improves.

Conclusion

Use static for things that belong to the type rather than to an object: constants, stateless helpers and shared counters that are genuinely shared. Everything that describes a particular thing should stay an instance member.

Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All Java notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.