library
beginnerThe final Keyword
Know every use of final: variables, methods, classes, and how it affects immutability and performance.
The final keyword has three uses in Java, each preventing a different kind of change:
Final variable = a picture frame bolted to the wall (can't move the frame, but can change the photo inside). Final class = a sealed envelope (can't open and modify it).
Key Concepts
1
1. Final variables — the reference cannot be reassigned after initialization. For primitives, the value is constant. For objects, the reference is constant but the object's state can still be mutated (final List can still have elements added). Must be initialized in the declaration, constructor, or instance initializer block. Blank finals (declared without value) must be assigned exactly once in every constructor.
2
2. Final methods — cannot be overridden by subclasses. Used to prevent alteration of critical behavior. The JVM may inline final methods for performance, though modern JIT does this automatically for effectively-final methods too.
3
3. Final classes — cannot be extended. String, Integer, and all wrapper classes are final. Used when the class's contract depends on its implementation not being altered (immutability guarantee, security).
4
final vs effectively final: since Java 8, a local variable that is never reassigned is 'effectively final' even without the keyword. Lambda expressions and anonymous classes can capture effectively final variables.
5
final does NOT make objects immutable — it only prevents reference reassignment. For immutability, all fields must be final AND the class must not leak mutable internal state.