Sub topic 5
Constants with `static final`
This chapter assumes you can define classes, create objects, use access modifiers, and understand basic inheritance. It focuses on values that belong to a class rather than to each object.
A static final field is assigned once for the class. static means one field is shared by every object of the class. final means the field reference or value cannot be assigned again after initialization.
Declaring constants
Java constants usually use uppercase letters with underscores between words. They are commonly declared public, static, and final.
public final class Limits {
public static final int MAX_USERS = 100;
public static final String DEFAULT_ROLE = "guest";
private Limits() {
}
}Code in another class can read these fields through the class name:
int allowed = Limits.MAX_USERS;
String role = Limits.DEFAULT_ROLE;Using the class name makes the ownership clear. These values do not belong to a particular Limits object.
The field must be assigned exactly once. You can assign it where you declare it, in a constructor for an instance field, or in a static initialization block for a static field.
`static final` references
For a primitive value, final prevents the value from changing. For an object reference, final prevents the reference from pointing to a different object. It does not automatically make the object immutable.
import java.util.ArrayList;
import java.util.List;
public final class Roles {
public static final List<String> NAMES = new ArrayList<>();
static {
NAMES.add("guest");
NAMES.add("admin");
}
private Roles() {
}
}The assignment to NAMES cannot happen again:
// Roles.NAMES = new ArrayList<>(); // compile errorHowever, the list itself is still mutable:
Roles.NAMES.add("auditor");If callers must not change the list, expose an unmodifiable view.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public final class Config {
public static final int MAX_USERS = 100;
public static final Map<String, Integer> LIMITS;
static {
Map<String, Integer> limits = new HashMap<>();
limits.put("free", 1);
limits.put("pro", 10);
LIMITS = Collections.unmodifiableMap(limits);
}
private Config() {
}
public static void main(String[] args) {
System.out.println(Config.MAX_USERS);
System.out.println(Config.LIMITS.get("pro"));
}
}The temporary local variable is built first. The final reference is assigned only after the map is ready.
Compile-time constants
A primitive or String static final field initialized with a constant expression can be a compile-time constant.
public final class HttpStatus {
public static final int OK = 200;
public static final String PREFIX = "HTTP";
}Java can substitute such values while compiling code that uses them. A value created with new, a method call, or a static block is not a compile-time constant, even when its field is static final.
| Declaration | Can be reassigned? | Can the object change? |
|---|---|---|
| `static final int COUNT = 1` | No | Not applicable |
| `static final List<String> NAMES` | No | Yes, unless the list is protected |
Static initialization blocks
A static initialization block runs once when Java initializes the class, before the class is used for the first time. It is useful when a constant needs several steps to construct.
A static block should remain simple. If initialization can fail, document or handle that failure because the class may become unusable when initialization throws an exception.
Choosing a constant design
Use static final for values that are shared and should not be reassigned, such as limits, names, or configuration defaults. Avoid putting mutable application state in a static final field merely because the reference is final. That state can still change and can make tests depend on execution order.
Exercise
Why does static final List<String> ITEMS still allow ITEMS.add("new"), and how can you prevent that change?
Show answer
final prevents the field from referencing another list, but it does not freeze the list's contents. Use an immutable list or expose an unmodifiable view, such as Collections.unmodifiableList(items).