Sub topic 13
When to Use Static and When to Avoid It
This chapter assumes you know how to declare static fields, static methods, and static final constants. It also assumes you know the static context rules and method hiding from earlier chapters, plus the basics of threads. The goal here is to turn those mechanics into design decisions.
The core question
A member should be static when it describes the class as a whole, not any one object. Ask three questions in order:
- Does the code need data from a particular object? If so, it must be an instance member.
- Might a subclass or a test need to replace this behavior? If so, use an instance method, because static methods are hidden and not overridden.
- Does the value change after startup? If so, treat a static field with suspicion. Shared mutable state has costs that constants do not.
Good fits for static
These uses are common and low risk.
| Use | Why static fits | Example |
|---|---|---|
| Constants | Value never changes and is the same for every object | `public static final int MAX_USERS = 100;` |
| Pure functions | Output depends only on arguments, no hidden state | `Math.max(a, b)` |
| Static factory methods | Creation happens before any object exists | `Temperature.ofFahrenheit(98.6)` |
| Static nested classes | Helper type needs no reference to an outer object | A `Builder` inside its target class |
| Counters or ID generators | State is truly one per program and made thread-safe | `AtomicInteger` in `IdGenerator` |
A pure function is the safest static method. It reads nothing except its parameters and writes nothing. It gives the same result for the same input, so it needs no instance and has nothing to mock.
Factory methods are static for a structural reason, not only a stylistic one. No object exists yet when you call them, so they cannot be instance methods. Keep the constructor private and give each creation path a name. Temperature.ofCelsius(20) is clearer than an overloaded constructor that takes a bare double.
Costs of static state
Hidden dependencies
A method that reads a static field has an input that does not appear in its signature. Reading the method's declaration tells you nothing about what it depends on. Callers cannot see the dependency, and they cannot supply a different one.
Testability
Tests should be independent and repeatable. A static mutable field lives as long as the class is loaded, so in a typical test run it survives from one test to the next. One test increments a static counter, and the next test sees the changed value. The tests then pass or fail depending on execution order.
Static calls are also hard to replace. If processOrder calls Instant.now() directly, a test cannot make it think it is next Tuesday. Passing a java.time.Clock into the object fixes this. The example below shows the pattern, with a clock the test controls:
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
class MutableClock extends Clock {
private Instant now;
MutableClock(Instant start) {
this.now = start;
}
void advance(Duration d) {
now = now.plus(d);
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
return this;
}
@Override
public Instant instant() {
return now;
}
}
public class TokenCheck {
private final Clock clock;
private final Instant issuedAt;
public TokenCheck(Clock clock) {
this.clock = clock;
this.issuedAt = clock.instant();
}
public boolean isExpired(Duration ttl) {
return clock.instant().isAfter(issuedAt.plus(ttl));
}
public static void main(String[] args) {
MutableClock clock = new MutableClock(Instant.parse("2026-01-01T00:00:00Z"));
TokenCheck token = new TokenCheck(clock);
System.out.println(token.isExpired(Duration.ofMinutes(30)));
clock.advance(Duration.ofMinutes(31));
System.out.println(token.isExpired(Duration.ofMinutes(30)));
}
}This prints false and then true, with no Thread.sleep. If isExpired had called Instant.now(), the test would need to wait 31 real minutes. The dependency on time is now visible in the constructor.
No polymorphism
Static methods are bound at compile time to the declared type. A call through an Animal variable runs Animal.describe() even when the object is a Dog. Any behavior you might want to vary by type, by configuration, or for a test double must therefore be an instance method. If you are tempted to write if (type == ...) inside a static method, that is a sign you want polymorphism.
Interfaces can declare static methods, but implementing classes do not inherit them. You call them as InterfaceName.method(). They suit helpers that belong with the interface, such as factory methods, and not behavior you want implementers to customize.
Thread safety
Every thread in the program shares a static field. A plain static int updated with ++ can lose updates, because ++ is a read, an add, and a write. Use AtomicInteger, ConcurrentHashMap, or a lock for static state that threads modify.
Immutability is the easier route. static final fields that refer to immutable values need no synchronization. A static final Map is only safe to share if you also wrap it with Collections.unmodifiableMap or use Map.of, since final stops reassignment but not mutation. Anything else in the map must be immutable too.
Lifetime and memory
A static field is a GC root for as long as its class stays loaded. Objects reachable from it cannot be collected. A static List that only ever grows is a memory leak. In application servers, where classes are loaded by a per-application class loader, a static reference that survives a redeploy can keep the whole old class loader alive.
Initialization failures
If a static block or static field initializer throws, the JVM wraps the exception in ExceptionInInitializerError. Every later attempt to use that class throws NoClassDefFoundError, and the original cause shows only in the first stack trace. Keep static initialization simple. Do not open connections or read files there, because a failure leaves the class unusable for the life of the JVM.
Singletons and global state
A common shortcut is a static field that holds "the" instance of a service:
public class Settings {
private static Settings current = new Settings();
public static Settings get() {
return current;
}
}This is global mutable state in disguise. Any code can call Settings.get(), so the dependency is invisible, and tests cannot swap it. In most application code, create the object once at startup and pass it to the classes that need it, either through constructors or a dependency injection framework. If you truly need exactly one instance, an enum with a single constant is the safest form, because the JVM guarantees one instance, even under serialization and reflection.
Utility classes: a middle path
A utility class is acceptable when each method is a pure function of its arguments, as in StringUtils.isBlank. Problems start when the class grows into a dumping ground. Warning signs include:
- Methods that read static fields or system state, such as the clock or environment variables.
- A name like
HelperorUtilwith unrelated methods inside. - Methods whose first parameter is always the same type. That method probably belongs on that type as an instance method.
Before adding a static helper, check whether the standard library already has one. Objects.requireNonNull, List.of, and String.isBlank() (Java 11) cover many cases that older code solved with custom utilities.
Static imports in moderation
import static shortens calls but hides where a method comes from. Use it for widely known names such as Math.max, Collectors.toList, or test assertions. Avoid wildcard static imports (import static java.lang.Math.*;) in production code. They make it hard to tell whether max is local, inherited, or imported, and two wildcards can introduce clashing names.
A review checklist
When you see static in a code review, check each point:
- Is the field
final? If not, why is the state global and not owned by an object? - If mutable, is it thread-safe, and is it ever reset between tests?
- Does the method read anything other than its arguments, such as time, randomness, files, or other static fields?
- Would a subclass, a test, or a second configuration ever need a different version?
- Could the method live on the type of its first argument?
Summary of trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Static constant | No allocation, inlined by the compiler, clear intent | None for primitives and immutable values |
| Static pure method | Simple to call, no object needed | Cannot be overridden or injected |
| Static mutable field | Easy global access | Hidden dependency, threading bugs, test coupling, memory retention |
| Static factory | Named creation, can cache or return subtypes | Harder to discover than constructors; subclassing is limited if the constructor is private |
| Instance member | Polymorphic, injectable, testable | Requires an object and passing it around |
Exercise
A class ReportGenerator has a method static String header() that returns "Report generated at " plus LocalDateTime.now(). Give two reasons this is a poor use of static, and describe one change that improves it.
Show answer
First, the method has a hidden dependency on the system clock, so its output differs on every call and a test cannot control it. Second, because it is static it cannot be overridden or replaced with a test double. Change it to an instance method on a ReportGenerator that receives a java.time.Clock in its constructor and calls LocalDateTime.now(clock). A test can then pass a fixed or mutable clock and assert on the exact text.
Exercise
You find public static final List<String> ALLOWED = new ArrayList<>(List.of("a", "b")); in shared code. What can go wrong, and how do you fix it?
Show answer
final only prevents reassigning ALLOWED. Any code can call ALLOWED.add(...) or clear(), which changes the list for every user and is not thread-safe, since ArrayList is not synchronized. Fix it by making the list immutable: public static final List<String> ALLOWED = List.of("a", "b");. Attempts to modify it then throw UnsupportedOperationException.
Exercise
For each member, say static or instance and give a one-sentence reason: (a) the number of seconds in a minute, (b) a user's email address, (c) a method that converts miles to kilometers, (d) a count of open database connections shared by all threads.
Show answer
(a) Static, because it is a constant that never changes, so declare it static final. (b) Instance, because each user has a different value. (c) Static, because it is a pure function of its argument and needs no object state. (d) Static only if the count is truly global, and then it must be a thread-safe type such as AtomicInteger. It is often better to put the count inside a connection-pool object that is passed in.