Sub topic 5
Constants with static final
This chapter assumes you can write classes with fields and constructors, you know public and private, and you have seen static fields shared by all instances. Here you will learn how static final creates constants, what the compiler does with them, and where they stop being constant.
What static final means
Two modifiers combine to make a constant:
staticmeans the field belongs to the class, so one copy exists no matter how many objects you create.finalmeans the field can be assigned only once. After that, the variable cannot point to anything else.
Together they give you a single, unchanging value that you read through the class name.
public class Limits {
public static final int MAX_USERS = 100;
public static final double TAX_RATE = 0.2;
public static final String DEFAULT_NAME = "guest";
public static void main(String[] args) {
System.out.println(Limits.MAX_USERS);
System.out.println(Limits.TAX_RATE * 50);
System.out.println(DEFAULT_NAME);
}
}A final field without static would be a separate constant in each object, which wastes memory when every object holds the same value. Adding static stores the value once.
Naming and visibility
By convention, constant names use UPPER_SNAKE_CASE: capital letters with underscores between words. This marks them as constants at every use site.
Make a constant public only when other classes need it. Otherwise use private static final. A private constant is an implementation detail you can change freely. A public one is part of your class's API, and changing it can break callers.
Assigning the value exactly once
A static final field must be assigned exactly once, in one of two places:
- In the declaration:
static final int MAX = 10; - In a static initializer block, if the field was declared without a value (a "blank final").
If you forget to assign it, or assign it twice, the code does not compile.
public class Broken {
static final int A; // never assigned: compile error
static final int B = 1;
static {
// B = 2; // compile error: cannot assign a value to final variable B
}
}Use the second form when the value needs several statements to build. This example builds a map and then wraps it so callers cannot change it:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Config {
public static final int MAX_USERS = 100;
public static final Map<String, Integer> LIMITS;
static {
Map<String, Integer> m = new HashMap<>();
m.put("free", 1);
m.put("pro", 10);
LIMITS = Collections.unmodifiableMap(m);
}
public static void main(String[] args) {
System.out.println(LIMITS.get("pro"));
}
}The local variable m exists only inside the block, so no code outside can reach the modifiable map. For small collections, Map.of("free", 1, "pro", 10) does the same in one line and returns an immutable map. Use the static block when the setup needs loops, conditions, or several steps.
final protects the variable, not the object
This is the most common misunderstanding. For a reference type, final fixes which object the variable points to. It says nothing about whether that object can change.
import java.util.ArrayList;
import java.util.List;
public class Registry {
public static final List<String> NAMES = new ArrayList<>();
public static void main(String[] args) {
NAMES.add("alice"); // allowed: the list itself is mutable
System.out.println(NAMES);
// NAMES = new ArrayList<>(); // compile error: the variable is final
}
}Any class can call Registry.NAMES.add(...) or clear(), so this is shared mutable state under a constant-looking name. Arrays have the same problem, and it is worse because an array cannot be made read-only at all:
import java.util.List;
public class Weekend {
// Bad: callers can write WEEKEND_DAYS[0] = "Mon"
public static final String[] WEEKEND_DAYS = {"Sat", "Sun"};
// Better: an immutable list
public static final List<String> WEEKEND = List.of("Sat", "Sun");
// Also fine: keep the array private and hand out copies
private static final String[] DAYS = {"Sat", "Sun"};
public static String[] days() {
return DAYS.clone();
}
public static void main(String[] args) {
WEEKEND_DAYS[0] = "Mon";
System.out.println(WEEKEND_DAYS[0]);
System.out.println(WEEKEND);
}
}This prints Mon and then [Sat, Sun]. The array constant was changed, and the list was not.
Immutable types such as String, Integer, and LocalDate are safe as constants because the object itself cannot change.
Compile-time constants
Java treats some static final fields specially. A field is a compile-time constant when all of these hold:
- Its type is a primitive or
String. - It is declared
final. - It is initialized in the declaration with a constant expression, such as a literal, or an operation on other constants.
public class Constants {
public static final int SECONDS_PER_MINUTE = 60;
public static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60; // constant expression
public static final String PREFIX = "app-";
public static final String KEY = PREFIX + "key"; // constant expression
public static final long NOW = System.currentTimeMillis(); // NOT a compile-time constant
public static final Integer BOXED = 5; // NOT: wrapper type
}NOW is initialized by a method call, and BOXED has a wrapper type, so neither qualifies. They are still constants in the sense that they are assigned once, but the compiler cannot know their values.
Consequence 1: values are copied into callers
The compiler replaces every use of a compile-time constant with its literal value. The bytecode of the calling class contains 100, not a reference to Config.MAX_USERS.
This causes a real maintenance problem. If library class A declares public static final int LIMIT = 10 and class B uses it, then you change LIMIT to 20 and recompile only A. Class B still uses 10. Ship a library with a changed constant and every client must be recompiled.
If a value may change between releases, avoid making it a compile-time constant. A method such as static int limit() { return 20; } is read at run time and does not have this problem.
Consequence 2: reading one does not initialize the class
Because the value is inlined, reading a compile-time constant does not trigger class initialization. Static blocks do not run. A non-compile-time constant does trigger it.
public class InlineDemo {
static class Holder {
static final int CONSTANT = 5;
static final int COMPUTED = Integer.parseInt("5");
static {
System.out.println("Holder initialized");
}
}
public static void main(String[] args) {
System.out.println(Holder.CONSTANT);
System.out.println("before computed");
System.out.println(Holder.COMPUTED);
}
}Output:
5
before computed
Holder initialized
5The first read prints 5 without running the static block. Reading COMPUTED forces the class to initialize, so Holder initialized appears just before the second 5.
Consequence 3: switch labels
A case label must be a constant expression, so compile-time constants can be used there:
public class Modes {
static final int FAST = 1;
static final int SLOW = 2;
static String describe(int mode) {
switch (mode) {
case FAST: return "fast";
case SLOW: return "slow";
default: return "unknown";
}
}
public static void main(String[] args) {
System.out.println(describe(2));
}
}If you remove final from FAST, the case FAST line no longer compiles.
Order matters inside a class
Static fields and static blocks run in the order they appear in the source. A blank final must be assigned before you read it. The compiler rejects most direct violations, but indirect ones, through a method call, compile and silently give the default value:
public class OrderTrap {
static final int FIRST = compute();
static final int SECOND = 10;
static int compute() {
return SECOND + 1; // SECOND is not yet assigned here
}
public static void main(String[] args) {
System.out.println(FIRST);
}
}This prints 1, not 11. Here SECOND is a compile-time constant, so you might expect the value 10 to be inlined and give 11. It does not: the 10 is inlined only where the compiler sees SECOND as a constant, and the result is still affected by what the class does at startup in more complex cases. Do not depend on this. The safe habit is to declare constants that others depend on first, and avoid calling methods from initializers that read other static fields.
Alternatives to constant values
A set of related int or String constants often hides a better design.
| Situation | Better choice |
|---|---|
| A fixed list of named options (`FAST`, `SLOW`) | An `enum`, which gives type safety and prevents invalid values |
| A fixed collection of values | `List.of`, `Set.of`, or `Map.of` |
| A value that may change between releases | A static method or configuration, not an inlined constant |
| Constants only used inside one class | `private static final` |
Avoid putting constants in an interface only so classes can implement it and use them without a prefix (the "constant interface" pattern). It leaks implementation details into the type of every implementing class. Put constants in a final class with a private constructor, or use a static import when you want to skip the prefix.
Summary of the rules
- Use
static finalfor values that are shared and never reassigned. - Name constants in
UPPER_SNAKE_CASE. - Assign them once, in the declaration or in a static block.
finalstops reassignment but does not make an object immutable.- Primitives and
Strings initialized with constant expressions are inlined by the compiler, which affects recompilation, class initialization, andswitchlabels. - Prefer immutable collections and enums to arrays and groups of loose
intconstants.
Exercise
A library class declares public static final int TIMEOUT = 30;. A separate application class prints Library.TIMEOUT. The library author changes the value to 60 and ships only the recompiled library file. What does the application print, and why? What change to the declaration would make the application see the new value without recompiling?
Show answer
It still prints 30. TIMEOUT is a compile-time constant (a primitive with a literal initializer), so the compiler copied the value 30 into the application's bytecode. To make the value read at run time, use an initializer that is not a constant expression, for example public static final int TIMEOUT = Integer.parseInt("30");, or expose it through a static method such as static int timeout() { return 60; }.
Exercise
Given public static final String[] COLORS = {"red", "green"};, explain why this is not a safe constant, then rewrite it so callers cannot change the contents.
Show answer
final only prevents assigning a new array to COLORS. Any caller can still write COLORS[0] = "blue" and change the shared array. A safe rewrite is public static final List<String> COLORS = List.of("red", "green");, which is immutable. Alternatively, make the array private static final and provide a method that returns COLORS.clone().