The final Keyword in Java
final means "cannot change after this point", but what exactly cannot change depends on where it is written: a variable cannot be reassigned, a method cannot be overridden, a class cannot be extended. This page shows each use and the compile errors that enforce it, explains effectively final variables and compile-time constants, including a constant that keeps its old value after a library update, and the limits of final: it does not make objects immutable.
Contents
What final means in each place
final
| On | Means | Typical use |
|---|---|---|
| A local variable or parameter | It can be assigned only once | Clarity; values captured by lambdas |
| An instance field | It must be assigned exactly once, in every constructor | Immutable objects, required dependencies |
A static | It must be assigned exactly once, when the class is initialized | Constants such as MAX_USERS |
| A method | Subclasses cannot override it | Protecting logic that other methods rely on |
| A class | It cannot be extended | Value classes and security-sensitive types such as String |
For variables, finalfinal List
final variables and fields
The program declares a constant, a blank final field (declared without a value and set in the constructor), a final list whose contents change, a final local assigned on two different paths, and a lambda that captures a variable that is never declared final.
import java.util.ArrayList;
import java.util.List;
public class FinalVariables {
static final int MAX_USERS = 100; // a constant
private final String id; // blank final: set once per object
FinalVariables(String id) {
this.id = id; // must be assigned in every constructor
}
public static void main(String[] args) {
final List<String> names = new ArrayList<>();
names.add("ann"); // allowed: the list itself can change
names.add("bob");
// names = new ArrayList<>(); // not allowed: the reference is final
System.out.println("final list contents changed: " + names);
final int limit;
if (args.length > 0) {
limit = 10; // a final local can be assigned once,
} else { // on each path
limit = 20;
}
System.out.println("limit = " + limit + ", MAX_USERS = " + MAX_USERS);
// Effectively final: never reassigned, so a lambda may capture it
String greeting = "hello";
Runnable r = () -> System.out.println(greeting + " from a lambda");
r.run();
System.out.println("id = " + new FinalVariables("u-1").id);
}
}
Output:
final list contents changed: [ann, bob]
limit = 20, MAX_USERS = 100
hello from a lambda
id = u-1
- The final list gained two names.
only stoppedfinal from being pointed at a different list.names was declared without a value and assigned in each branch of thelimit . The compiler accepts this because, on every path, it is assigned exactly once.if is not declaredgreeting , but it is never reassigned, so it is effectively final (Java 8), and the lambda may capture it. Lambdas and anonymous classes capture a copy of the value, so Java requires that the variable cannot change afterwards, or the copy and the variable could disagree.final- A blank final field such as
must be assigned in every constructor. This is how classes guarantee that a required value is always present.id
The rules javac enforces
To show each rule rather than describe it, the program compiles two small files that break them and prints javac's errors. The first file breaks the assignment and inheritance rules. The second breaks the flow rules, which javac checks in a later phase, so they need a file of their own to be reported.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.tools.ToolProvider;
// Compiles code that breaks each rule of final and prints javac's errors
public class FinalRules {
static final String ASSIGNMENTS = """
class Assignments {
static final int LIMIT = 10;
void reassign() {
LIMIT = 11; // error: final field
final int x = 1;
x = 2; // error: final local
}
}
final class Leaf { }
class Sub extends Leaf { } // error: final class
class Base { final void run() { } }
class Derived extends Base { void run() { } } // error: final method
""";
// javac checks definite assignment in a later phase, so these go in a second file
static final String FLOW = """
import java.util.List;
class Flow {
final String id; // blank final
Flow(boolean flag) {
if (flag) {
id = "a";
}
} // error: not set on every path
void capture(List<Runnable> tasks) {
int count = 0;
count++; // count is not effectively final
tasks.add(() -> System.out.println(count)); // error
}
}
""";
public static void main(String[] args) throws IOException {
compile("Assignments.java", ASSIGNMENTS);
compile("Flow.java", FLOW);
}
static void compile(String name, String code) throws IOException {
Path dir = Files.createTempDirectory("final");
Path file = dir.resolve(name);
Files.writeString(file, code);
ByteArrayOutputStream err = new ByteArrayOutputStream();
ToolProvider.getSystemJavaCompiler().run(null, null,
new PrintStream(err, true, StandardCharsets.UTF_8),
"-d", dir.toString(), file.toString());
err.toString(StandardCharsets.UTF_8).lines()
.filter(l -> l.startsWith(file.toString()))
.map(l -> l.substring(dir.toString().length() + 1))
.forEach(System.out::println);
}
}
Output:
Assignments.java:12: error: cannot inherit from final Leaf
Assignments.java:5: error: cannot assign a value to static final variable LIMIT
Assignments.java:7: error: cannot assign a value to final variable x
Assignments.java:15: error: run() in Derived cannot override run() in Base
Flow.java:10: error: variable id might not have been initialized
Flow.java:15: error: local variables referenced from a lambda expression must be final or effectively final
- Assigning to a final field or local is rejected: "cannot assign a value to final variable".
- Extending a final class ("cannot inherit from final") and overriding a final method ("cannot override") are rejected.
- "variable id might not have been initialized": the constructor sets
only whenid is true. javac's definite assignment analysis follows every path through the code.flag - The lambda captured
, which is incremented, so it is not effectively final. The usual fixes are to copy it into a new local before the lambda, or to use ancount if the lambda must update shared state.AtomicInteger
final methods and classes
The program protects the withdrawal check of an account by making the method final, while leaving describe
import java.lang.reflect.Modifier;
import java.util.ArrayList;
public class FinalMethodsClasses {
static class Account {
private long balance = 100;
// final: subclasses cannot change how withdrawals are validated
final boolean withdraw(long amount) {
if (amount <= 0 || amount > balance) {
return false;
}
balance -= amount;
return true;
}
String describe() { // not final: may be overridden
return "account";
}
}
static class Savings extends Account {
@Override
String describe() {
return "savings account";
}
// boolean withdraw(long amount) { ... } would not compile: withdraw is final
}
public static void main(String[] args) {
Account a = new Savings();
System.out.println(a.describe());
System.out.println("withdraw 30: " + a.withdraw(30) + ", withdraw 500: " + a.withdraw(500));
// Final classes in the JDK cannot be subclassed at all
for (Class<?> c : new Class<?>[] {String.class, Integer.class, ArrayList.class}) {
boolean isFinal = Modifier.isFinal(c.getModifiers());
System.out.println(c.getSimpleName() + " is final: " + isFinal);
}
}
}
Output:
savings account
withdraw 30: true, withdraw 500: false
String is final: true
Integer is final: true
ArrayList is final: false
overrodeSavings but could not overridedescribe , so the balance check cannot be bypassed by a subclass. The rejected withdrawal of 500 shows the check still running.withdraw andString are final. IfInteger could be subclassed, a subclass could make a "string" that changes after a security check or a hash lookup.String is designed for extension and is not final.ArrayList- Records and enums are implicitly final. Since Java 17,
sealed classes offer a middle ground: a class that may be extended only by named subclasses. - A common belief is that
makes methods faster. Modern JITs inline non-final methods too, when only one implementation is loaded, so usefinal for design reasons, not speed.final
Compile-time constants
A static finalStringcasestatic final
public class ConstantsInlined {
static final int INLINED = 42; // compile-time constant
static final int COMPUTED = Integer.parseInt("42"); // assigned at run time
static final StringBuilder LOG = new StringBuilder();
public static void main(String[] args) {
// A switch label needs a compile-time constant
int value = 42;
switch (value) {
case INLINED -> System.out.println("matched the constant");
default -> System.out.println("no match");
}
// case COMPUTED -> ... would not compile: not a constant expression
System.out.println("COMPUTED = " + COMPUTED);
// final does not make the object immutable
LOG.append("first ");
LOG.append("second");
System.out.println("final StringBuilder still changes: " + LOG);
}
}
Output:
matched the constant
COMPUTED = 42
final StringBuilder still changes: first second
compiles because 42 is known at compile time.case INLINED has the same value, but it comes from a method call, so it is not a constant expression and cannot be aCOMPUTED label.case isLOG , but thestatic final it points to keeps changing. A "constant" holding a mutable object is a shared global variable.StringBuilder
The stale constant problem
Because constants are copied into the classes that use them, changing a constant in a library does not reach code that was compiled against the old version. The program builds a tiny library (ConfigAppAppConfigConfig
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.spi.ToolProvider;
// Shows that compile-time constants are copied into the classes that use them
public class StaleConstant {
static void javac(Path dir, String... files) {
StringWriter out = new StringWriter();
String[] args = new String[files.length + 2];
args[0] = "-d";
args[1] = dir.toString();
for (int i = 0; i < files.length; i++) {
args[i + 2] = dir.resolve(files[i]).toString();
}
ToolProvider.findFirst("javac").orElseThrow()
.run(new PrintWriter(out), new PrintWriter(out), args);
}
static Object run(Path dir) throws Exception {
try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()}, null)) {
return loader.loadClass("App").getMethod("limits").invoke(null);
}
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("stale");
Files.writeString(dir.resolve("Config.java"), """
public class Config {
public static final int MAX = 10; // constant
public static final Integer BOXED = Integer.valueOf(10); // not a constant
}
""");
Files.writeString(dir.resolve("App.java"), """
public class App {
public static String limits() {
return "MAX=" + Config.MAX + ", BOXED=" + Config.BOXED;
}
}
""");
javac(dir, "Config.java", "App.java");
System.out.println("both compiled: " + run(dir));
// Change the library and recompile ONLY Config, as when a dependency is upgraded
Files.writeString(dir.resolve("Config.java"), """
public class Config {
public static final int MAX = 99;
public static final Integer BOXED = Integer.valueOf(99);
}
""");
javac(dir, "Config.java");
System.out.println("only Config recompiled: " + run(dir));
}
}
Output:
both compiled: MAX=10, BOXED=10
only Config recompiled: MAX=10, BOXED=99
- After only
was recompiled,Config still read 10:MAX contains the number 10 itself and never looks atApp.class .Config , which is not a compile-time constant, is read fromBOXED when the program runs, so it showed the new value 99.Config - This is why public constants in libraries should be values that truly never change, such as mathematical constants. For values that might change between versions, use a static method or a non-constant field.
static final fields computed at startup
A static final
import java.util.Map;
public class StaticFinalInit {
// A static final computed at class initialization, from configuration
static class Settings {
static final Map<String, String> ENV = Map.of("PORT", "eighty");
static final int PORT;
static {
System.out.println(" Settings is being initialized");
PORT = Integer.parseInt(ENV.get("PORT")); // fails: "eighty" is not a number
}
}
// The lazy holder idiom: the inner class is initialized only when first used
static class Registry {
private static class Holder {
static final Registry INSTANCE = new Registry();
}
Registry() {
System.out.println(" Registry created");
}
static Registry get() {
return Holder.INSTANCE;
}
}
public static void main(String[] args) {
System.out.println("first access to Settings.PORT:");
try {
System.out.println(Settings.PORT);
} catch (ExceptionInInitializerError e) {
System.out.println(" ExceptionInInitializerError caused by "
+ e.getCause().getClass().getSimpleName());
}
System.out.println("second access to Settings.PORT:");
try {
System.out.println(Settings.PORT);
} catch (NoClassDefFoundError e) {
System.out.println(" NoClassDefFoundError: " + e.getMessage());
}
System.out.println("before Registry.get()");
Registry a = Registry.get();
Registry b = Registry.get();
System.out.println("same instance: " + (a == b));
}
}
Output:
first access to Settings.PORT:
Settings is being initialized
ExceptionInInitializerError caused by NumberFormatException
second access to Settings.PORT:
NoClassDefFoundError: Could not initialize class StaticFinalInit$Settings
before Registry.get()
Registry created
same instance: true
- The first access ran the static block, and
threw. The JVM wrapped it inInteger.parseInt("eighty") , anExceptionInInitializerError that ordinaryError blocks do not catch.catch (Exception e) - The second access did not retry. The class was marked as failed, and every later use threw
. In logs this second error is often the only one people notice, and it is confusing because the class file exists. The real cause is in the first error.NoClassDefFoundError: Could not initialize class - Keep static initializers simple. Configuration that can be wrong is better read in a method, or in a constructor of an object created at startup, where a failure can be reported clearly and retried.
- The lazy holder idiom puts a
instance in a nested class. The JVM initializesstatic final only whenHolder first touches it, so "Registry created" printed after "before Registry.get()", and class initialization is thread-safe by specification, so no locking is needed. For singletons, a one-constantget()enum is simpler still.
What final does not protect against
final
import java.lang.reflect.Field;
public class FinalAndReflection {
static class Box {
private final int size = Integer.parseInt("5"); // final, but not a constant
private final int constant = 5; // a compile-time constant
int size() {
return size;
}
int constant() {
return constant;
}
}
record Point(int x) { }
public static void main(String[] args) throws Exception {
Box box = new Box();
Field size = Box.class.getDeclaredField("size");
size.setAccessible(true);
size.setInt(box, 50);
System.out.println("final instance field changed by reflection: " + box.size());
Field constant = Box.class.getDeclaredField("constant");
constant.setAccessible(true);
constant.setInt(box, 50);
System.out.println("constant field set to 50, field holds " + constant.getInt(box)
+ ", but code reads " + box.constant());
Field x = Point.class.getDeclaredField("x");
x.setAccessible(true);
try {
x.setInt(new Point(1), 2);
} catch (IllegalAccessException e) {
System.out.println("record field: IllegalAccessException");
}
}
}
Output:
final instance field changed by reflection: 50
constant field set to 50, field holds 50, but code reads 5
record field: IllegalAccessException
- With
, reflection changed the finalsetAccessible(true) field from 5 to 50. Frameworks such as serialization libraries rely on this.size fields cannot be changed this way at all.static final - For the constant field, the field itself was changed to 50, but
still returned 5, because the compiler had copied the value 5 into the method.constant() - Record fields are truly final: changing them by reflection throws
even afterIllegalAccessException . The JDK does the same for hidden classes, and the OpenJDK project is working to restrict changes to final fields in general.setAccessible(true) - Final fields also have a guarantee in the
Java Memory Model : once a constructor finishes, other threads see the values of final fields correctly, without synchronization, as long as did not escape during construction.this
When to use final
| Where | Recommendation |
|---|---|
| Fields | Make them final |
| Constants | static final |
| Local variables and parameters | Optional; effectively final is enough for lambdas, and many teams leave final |
| Methods | Template methods and methods that enforce invariants in classes designed for extension |
| Classes | Value classes and classes not designed for extension; or use a record |