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 is a promise checked by the compiler: the thing it marks will not be changed later. It appears in four places, with a different meaning in each:

The uses of final
OnMeansTypical use
A local variable or parameterIt can be assigned only onceClarity; values captured by lambdas
An instance fieldIt must be assigned exactly once, in every constructorImmutable objects, required dependencies
A static fieldIt must be assigned exactly once, when the class is initializedConstants such as MAX_USERS
A methodSubclasses cannot override itProtecting logic that other methods rely on
A classIt cannot be extendedValue classes and security-sensitive types such as String

For variables, final fixes the reference, not the object it points to. A final List can still have elements added; it just cannot be made to point to a different list. Making the object itself unchangeable is a separate design, covered on the immutability page.

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.

Java
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:

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. final only stopped names from being pointed at a different list.
  • limit was declared without a value and assigned in each branch of the if. The compiler accepts this because, on every path, it is assigned exactly once.
  • greeting is not declared final, 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.
  • A blank final field such as id must be assigned in every constructor. This is how classes guarantee that a required value is always present.

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.

Java
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:

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 id only when flag is true. javac's definite assignment analysis follows every path through the code.
  • The lambda captured count, 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 an AtomicInteger if the lambda must update shared state.

final methods and classes

The program protects the withdrawal check of an account by making the method final, while leaving describe open for subclasses, and then asks which well-known JDK classes are final.

Java
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:

Output
savings account
withdraw 30: true, withdraw 500: false
String is final: true
Integer is final: true
ArrayList is final: false
  • Savings overrode describe but could not override withdraw, so the balance check cannot be bypassed by a subclass. The rejected withdrawal of 500 shows the check still running.
  • String and Integer are final. If String could be subclassed, a subclass could make a "string" that changes after a security check or a hash lookup. ArrayList is designed for extension and is not final.
  • 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 final makes methods faster. Modern JITs inline non-final methods too, when only one implementation is loaded, so use final for design reasons, not speed.

Compile-time constants

A static final field of a primitive type or String, initialized with a constant expression, is a compile-time constant. The compiler treats it specially: it can be used in case labels, and its value is copied into the code that uses it. The program compares such a constant with a static final computed at run time, and a final reference to a mutable object.

Java
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:

Output
matched the constant
COMPUTED = 42
final StringBuilder still changes: first second
  • case INLINED compiles because 42 is known at compile time. COMPUTED has the same value, but it comes from a method call, so it is not a constant expression and cannot be a case label.
  • LOG is static final, but the StringBuilder it points to keeps changing. A "constant" holding a mutable object is a shared global variable.

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 (Config) and an application (App) in a temporary folder, runs App, then changes both values in Config and recompiles only Config, as happens when a dependency JAR is upgraded without rebuilding the application.

Java
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:

Output
both compiled:         MAX=10, BOXED=10
only Config recompiled: MAX=10, BOXED=99
  • After only Config was recompiled, MAX still read 10: App.class contains the number 10 itself and never looks at Config. BOXED, which is not a compile-time constant, is read from Config when the program runs, so it showed the new value 99.
  • 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 field that is not a compile-time constant is assigned when its class is initialized, the first time the class is used. If that assignment throws, the class is broken for the rest of the program's life. The program reads a port number from configuration in a static block, with a configuration value that is not a number, and accesses the field twice. It then shows the lazy holder idiom, which uses the same initialization rules on purpose.

Java
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:

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 Integer.parseInt("eighty") threw. The JVM wrapped it in ExceptionInInitializerError, an Error that ordinary catch (Exception e) blocks do not catch.
  • The second access did not retry. The class was marked as failed, and every later use threw NoClassDefFoundError: Could not initialize class. 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.
  • 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 static final instance in a nested class. The JVM initializes Holder only when get() 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-constant enum is simpler still.

What final does not protect against

final is enforced by the compiler and, for fields, by the JVM, but reflection can still change some final fields. The program changes a final instance field, tries the same on a compile-time constant field, and then on a record component.

Java
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:

Output
final instance field changed by reflection: 50
constant field set to 50, field holds 50, but code reads 5
record field: IllegalAccessException
  • With setAccessible(true), reflection changed the final size field from 5 to 50. Frameworks such as serialization libraries rely on this. static final fields cannot be changed this way at all.
  • For the constant field, the field itself was changed to 50, but constant() still returned 5, because the compiler had copied the value 5 into the method.
  • Record fields are truly final: changing them by reflection throws IllegalAccessException even after setAccessible(true). The JDK does the same for hidden classes, and the OpenJDK project is working to restrict changes to final fields in general.
  • 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 this did not escape during construction.

When to use final

Guidelines
WhereRecommendation
FieldsMake them final unless they must change; it documents intent and gives thread-safety guarantees
Constantsstatic final with an UPPER_CASE name; only for values that never change between versions
Local variables and parametersOptional; effectively final is enough for lambdas, and many teams leave final off for readability
MethodsTemplate methods and methods that enforce invariants in classes designed for extension
ClassesValue classes and classes not designed for extension; or use a record