Video in progress

Junior ☕ Core Java

What does the final keyword mean on a variable, a method and a class?

On a variable, the value (or reference) can be assigned only once; on a method, a subclass can't override it; on a class, it can't be extended.

📖 Answer

final int max = 10;
max = 20;                 // compile error

final List<String> list = new ArrayList<>();
list.add("ok");           // allowed! the reference is final, not the object
list = new ArrayList<>(); // error

This is the most common confusion: a final reference doesn't make the object immutable. If you need an immutable list, use List.of(...) or List.copyOf(...).

public final class Money { ... }       // can't be extended (String is the same)

class Base {
    public final void audit() { ... }  // a subclass can't change it
}

What it gives you in practice:

  • making dependencies passed through the constructor final means they can't be changed by accident later;
  • under the Java Memory Model, final fields are guaranteed to be visible correctly to other threads once the constructor finishes;
  • inside a lambda you can only use final or "effectively final" local variables.