Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 201 ยท Object-Oriented Programming

The final Keyword Everywhere

Learn every use of Java final - local variables, parameters, fields, methods and classes, blank finals, effectively final, illegal combinations and final vs immutable.

final is one keyword with one idea behind it: this can't be changed later. What "this" is depends on where you write it. On a variable, the value can't be reassigned. On a method, subclasses can't override it. On a class, nobody can extend it. Each use removes one kind of change, and each removal is a promise that readers, the compiler and the JVM can rely on.

You met final variables and static final constants in Constants and final, and final classes and methods briefly in Inheritance. This lesson puts every use side by side and goes deeper: final parameters and the places where Java makes variables final for you, blank final fields and constructor rules, why final methods protect constructors and template methods, final classes as a design choice, the combinations the compiler forbids, the thread-safety guarantee of final fields, and the difference between final and immutable.

final at a glance

Where What final prevents Example
Local variable Assigning a second time final int max = 10;
Parameter Reassigning the parameter inside the method void send(final String to)
Instance field Changing the field after the constructor finishes private final String id;
Static field Changing it after class initialization static final int PORT = 8080;
Method Overriding in a subclass final void validate()
Class Extending the class final class Money

Notice what's not on the list: final never makes an object unchangeable. It freezes a variable's reference, a method's body or a class's hierarchy. Keep that in mind; we'll come back to it at the end.

final variables and parameters

A final local variable must be assigned exactly once. The assignment doesn't have to be on the declaration line: the compiler's definite assignment analysis checks that every path assigns it exactly once before it's read.

Java final locals, deferred assignment and parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

If one branch forgot to assign group, reading it would fail with variable group might not have been initialized; if a branch assigned it twice, you'd get variable group might already have been assigned. Using a deferred final like this is a nice way to say "this value is decided once, by this logic," and it's often clearer than a variable that gets overwritten. (A switch expression is the other clean option.)

final parameters

Marking a parameter final stops the method body from reassigning it. It has no effect on the caller: Java passes arguments by value (Parameters and Return Values), so reassigning a parameter never changed the caller's variable anyway. The benefit is purely for readers of a long method: the parameter means the same thing on every line.

Teams differ on this. Many style guides skip final on parameters because it adds noise to every signature and the compiler already tracks whether a parameter is reassigned (it's then effectively final). A common compromise is a rule, enforced by a linter, that parameters are never reassigned, with or without the keyword.

Places where Java makes variables final for you

Some variables are final even if you don't write the keyword:

  • Multi-catch parameters: in catch (IOException | SQLException e), e is implicitly final (Exceptions and try-catch).
  • try-with-resources variables: resources declared in try (var in = ...) are implicitly final (try-with-resources).
  • Record components: the fields behind a record are private final.
  • Interface fields: any field declared in an interface is implicitly public static final.
  • Enum constants: each constant is a public static final field of the enum.

You can also write final on a for-each loop variable, for (final String line : lines), which is legal because each iteration gets a fresh variable. A classic for (int i = 0; ...; i++) counter can't be final, since i++ reassigns it.

final fields

A final instance field must be assigned exactly once per object, and that must happen by the end of construction: at the declaration, in an instance initializer block, or in every constructor. A static final field must be assigned at its declaration or in a static block.

Java Blank final fields and constructor chaining

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The no-argument constructor doesn't assign anything itself; it delegates to this(...), which does. The compiler accepts that, because every path through every constructor ends with each final field assigned once. If a constructor forgot one, the error is variable holder might not have been initialized, reported at that constructor.

Two practical rules follow:

  • Make fields final by default. A field that never changes after construction should say so. It documents the design, catches accidental reassignments in methods, and enables the thread-safety guarantee below. Remove final only when a field really needs to change.
  • A final collection field still allows add and remove. As notes shows, the field always refers to the same list, but the list's contents change. That's often exactly what you want for an object's internal state. When it isn't, see Immutable Classes.

The thread-safety guarantee

The Java Memory Model gives final fields a special promise: once a constructor finishes, any thread that obtains a reference to the object sees the correct values of its final fields, even without synchronization. Non-final fields don't have this guarantee; without proper publication, another thread could briefly see their default values (0, null).

The promise has one condition: the constructor must not let this escape before it finishes, for example by registering the object in a static list or starting a thread that uses it. This guarantee is one reason immutable objects with final fields can be shared freely between threads (Synchronization and Race Conditions).

final methods

A final method can be called and inherited like any other method, but a subclass can't override it. Trying to gives overridden method is final.

Why forbid overriding? Because some methods are part of a class's guarantees. Two classic cases:

  1. Template methods. A base class defines the fixed sequence of steps in a final method and lets subclasses fill in the individual steps (Abstraction and Abstract Classes). If subclasses could override the sequence itself, they could skip validation or logging.
  2. Methods called from constructors. If a constructor calls an overridable method, the subclass version runs before the subclass's own fields are initialized. That's a real and confusing bug:
Java Why constructors should only call final or private methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows a button labeled null first: Widget() runs before the rest of Button's constructor (and before its field initializers), so the overriding method sees a final field that hasn't been assigned yet. Yes, a final field can be observed with its default value, but only during construction, and only through this kind of leak. The call to the final kind() is harmless, because no subclass can replace it. The fix is a rule: constructors should call only private, static or final methods, so no subclass code can run before the subclass is ready.

One twist: had label been declared as private final String label = "OK";, the method would print OK even during Widget(). A final field initialized with a constant expression is a constant variable, and the compiler replaces reads of it with the value itself (Constants and final). Any other initializer, such as a method call or a constructor parameter, shows the null.

final, private and static methods

  • A private method can't be overridden anyway (subclasses don't see it), so private final is redundant. The compiler accepts it, but it adds nothing.
  • A static method isn't overridden; a subclass can declare a static method with the same signature that hides it. static final forbids that hiding. It's rarely needed.
  • Performance isn't a good reason for final methods. Old advice said final lets the compiler inline calls; modern JIT compilers inline non-final methods too, as long as no loaded subclass overrides them. Use final for design, not speed.

final classes

A final class can't be extended: class Special extends Money fails with cannot inherit from final Money. Every method of a final class is effectively final as well.

Many core classes are final: String, the wrapper classes (Integer, Double, ...), LocalDate and the rest of java.time, Optional, and every record and enum (an enum with constant-specific bodies is implicitly sealed instead). Making a class final:

  • protects invariants: a subclass of String could pretend to be immutable while changing its contents, which would break every HashMap that uses it as a key;
  • keeps your options open: once people subclass your class, every protected or overridable detail becomes part of your public contract;
  • makes the design explicit: a class is either designed for inheritance (documented hooks, protected methods, careful constructors) or it's final.

That last point is a well-known guideline: design and document for inheritance, or else prohibit it. If you're not sure, start with final; you can remove it later without breaking anyone, while adding it later breaks every existing subclass.

When a class should have a few known subclasses but no unknown ones, final is too strict. That's what sealed classes are for. Each permitted subclass of a sealed class must itself be final, sealed or non-sealed, which is one more place where you'll write final often.

Combinations the compiler rejects

final conflicts with any modifier that requires a later change:

Java Illegal uses of final (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This file doesn't compile on purpose. The first two errors read illegal combination of modifiers: abstract and final; the interface method gives modifier final not allowed here, and so does the constructor. (A default method in an interface can't be final either: interfaces exist to be implemented.) Fields in interfaces, on the other hand, are always final, so writing final there is allowed but redundant.

Effectively final and captured variables

A local variable that is never reassigned after initialization is effectively final, and lambdas, anonymous classes and local classes can only use local variables that are final or effectively final:

Java Capturing effectively final variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The reason: a lambda or anonymous class receives a copy of the variable's value when it's created. If the variable could change later, the copy and the original would disagree. Uncomment the last line and the compiler reports local variables referenced from a lambda expression must be final or effectively final (and the inner-class equivalent), even though the reassignment comes after the captures. Fields aren't affected by this rule, since lambdas reach them through this. More on capturing in Lambda Expressions.

final vs immutable

This is the most common confusion about final, so here it is precisely:

Can the variable point elsewhere? Can the object's state change?
List<String> a = new ArrayList<>(); yes yes
final List<String> b = new ArrayList<>(); no yes: b.add("x") works
List<String> c = List.of("x"); yes no: c.add("y") throws
final List<String> d = List.of("x"); no no
  • final is about the variable (a compile-time rule about assignment).
  • Immutability is about the object (a property of its class: no methods change its state, and its fields are final and refer to immutable things).

A truly constant value needs both: a final variable pointing to an immutable object. That's why public static final List<String> NAMES = new ArrayList<>(); is a bug waiting to happen: anyone can call NAMES.clear(). Use List.of(...) there. Building your own immutable types is covered in Immutable Classes; records give you shallowly immutable classes for free.

Deep reflection (Field.setAccessible(true) then set) can still change an ordinary final instance field today, which some serialization and mocking libraries rely on. It can't change static final fields or record fields, and newer JDK releases are moving toward forbidding it entirely, so never design around it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? final List<Integer> nums = new ArrayList<>(); nums.add(1); nums.add(2); IO.println(nums);

    final stops nums from being reassigned, but the ArrayList it points to can still change. add works normally.
  2. 2. A class has private final String name; and two constructors. One assigns name, the other calls this(\"default\"). Does it compile?

    A constructor that starts with this(...) delegates field initialization to the other constructor, so on every path name is assigned exactly once.
  3. 3. A base class constructor calls an overridable method. The subclass overrides it to print a final String field that the subclass constructor assigns from its parameter, after super(). What is printed while the base constructor runs?

    The superclass constructor runs before the subclass's field initializers, so the overriding method sees the field's default value, null. Constructors should only call private, static or final methods.
  4. 4. Which declaration compiles?

    A final method in a final class is redundant but legal. abstract and final contradict each other, interface methods can't be final, and constructors can't have the final modifier.
  5. 5. Why does int total = 0; list.forEach(x -> total += x); fail to compile?

    The lambda would capture a copy of total, so Java forbids reassigning a captured local. Use a stream sum, a loop, or a field instead.

Summary

  • final means "can't be changed later": no reassignment for variables, no overriding for methods, no subclassing for classes.
  • Final locals and fields can be assigned later (blank finals), but exactly once on every path; final fields must be set by the end of every constructor.
  • Java makes some variables final for you: multi-catch parameters, try-with-resources variables, record fields, interface fields and enum constants.
  • Final fields come with a thread-safety guarantee once construction finishes, as long as this doesn't escape the constructor.
  • Make methods called from constructors private, static or final; use final methods to protect template methods and invariants.
  • Make classes final unless they're designed for inheritance; use sealed classes for "only these subclasses."
  • abstract final, final interface methods and final constructors are compile errors.
  • final freezes a reference, not an object: combine a final variable with an immutable object for a real constant.

Next: Packages and Imports, where you'll organize classes into packages and learn every form of import.