Constants (final)
The final Keyword
A final variable
public class FinalDemo {
public static void main(String[] args) {
final int MAX_ATTEMPTS = 3;
System.out.println(MAX_ATTEMPTS);
// MAX_ATTEMPTS = 5; // compile-time error!
}
}3
Naming Convention: ALL_CAPS_WITH_UNDERSCORES
By strong convention, Java constants are named entirely in uppercase letters, with words separated by underscores. This makes constants instantly recognizable wherever they appear in code, distinguishing them from regular variables and methods (which use camelCase).
Good: MAX_ATTEMPTS, DEFAULT_TIMEOUT, PI, TAX_RATE
Not idiomatic: maxAttempts, defaultTimeout (fine for regular variables, but not the convention for constants)
static final: The Idiomatic Class-Level Constant
A class-level constant
public class Circle {
static final double PI = 3.14159;
double radius;
Circle(double radius) {
this.radius = radius;
}
double area() {
return PI * radius * radius;
}
public static void main(String[] args) {
Circle c1 = new Circle(2.0);
Circle c2 = new Circle(5.0);
System.out.println("Area 1: " + c1.area());
System.out.println("Area 2: " + c2.area());
System.out.println("Shared constant: " + Circle.PI);
}
}Area 1: 12.56636 Area 2: 78.53975 Shared constant: 3.14159
final Prevents Reassignment — Not Mutation
A final list is not an immutable list
import java.util.ArrayList;
import java.util.List;
public class FinalListDemo {
public static void main(String[] args) {
final List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.remove("Alice");
System.out.println(names); // [Bob] — the object WAS mutated
// names = new ArrayList<>(); // compile-time error!
// Reassigning the reference itself is what's forbidden.
}
}[Bob]
final on Method Parameters and Fields
final on a field, assigned in the constructor
public class User {
final String username; // must be set exactly once
User(String username) {
this.username = username; // allowed: first assignment
}
public static void main(String[] args) {
User u = new User("admin");
System.out.println(u.username);
}
}admin
Applied To | What final Guarantees |
Local variable | Can only be assigned once |
static final field | One shared value across the whole class, set once |
Instance field | Must be assigned exactly once (often in the constructor) |
Reference-type variable | The reference can't change — the object it points to still can |