Constants with final in Java
final variables, static final constants and naming.
final can never change... yet a final StringBuilder happily changes its contents. Is final lying?Assign once, then locked
final means a variable can be assigned exactly once. Any later assignment is a compile error.
final int limit = 10;
limit = 20; // error: cannot assign a
// value to final variableBlank finals
You can declare a final variable without a value and assign it later, once. That's called a blank final. It must be definitely assigned before it's read.
final String label;
label = "ready"; // first: ok
// label = "go"; // second: errorClass constants
A fixed value shared by a whole class is declared static final and named in UPPER_SNAKE_CASE. Java has no working const keyword: const is reserved but does nothing.
public static final int MAX_USERS = 100;
static final double TAX_RATE = 0.2;Your turn
A StringBuilder is a piece of text you can change. It's final here. What does this print?
final StringBuilder sb =
new StringBuilder("Hi");
sb.append("!");
System.out.println(sb);HiHi!Compile error
Show the answer
Hi! final locks the variable, meaning which object it points to. It does not freeze the object. append changes the object, and that's allowed.
What final blocks
final StringBuilder sb =
new StringBuilder("Hi");
sb = new StringBuilder();Pointing a final variable at a different object is a compile error.
final StringBuilder sb =
new StringBuilder("Hi");
sb.append("!");Changing the object it points to is fine: final reference is not the same as an immutable object.
In real projects
Magic numbers like 0.2 scattered through code are a maintenance nightmare. A named constant like TAX_RATE explains itself and changes in one place. Many teams also mark locals final to signal they never change.
Key takeaways
- final variable: assigned exactly once
- Constants: static final int MAX_USERS = 100;
- A blank final can be assigned later, but only once
- final reference ≠ immutable object
Constants like static final int MAX = 100; are copied (inlined) into every class that uses them at compile time. Change MAX without recompiling those classes and they keep using the old 100!
Practice questions
What does this print?
final int limit = 10;
limit = 20;
System.out.println(limit);- Compile error
- 20
- 10
- Throws IllegalStateException
Check your answer
Compile error. limit is final and already assigned, so javac reports "cannot assign a value to final variable limit".
Which keyword makes this a constant?
public static ___ int MAX_USERS = 100;- const
- final
- static
- constant
Check your answer
final. Java uses static final for constants. const is a reserved word but isn't used by the language at all.