final Keyword

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

The final keyword is an access modifier used to restrict the user from changing things. It can be applied to:

  1. Variables: The variable’s value cannot be changed (it becomes a constant).
  2. Methods: The method cannot be overridden by subclasses.
  3. Classes: The class cannot be inherited (subclassed).

Concept

1. Final Variables

When a variable is declared final, it can only be initialized once. For primitive types, the value is locked. For reference types, the reference is locked (you can’t point the variable to a different object), but the internal state of the object can still be mutated.

2. Final Methods

If you mark a method as final in a parent class, no child class is allowed to @Override it. This is useful for preventing core algorithms or security-sensitive methods from being altered.

3. Final Classes

If a class is marked final, it cannot be extended. The String class and all wrapper classes (like Integer) are final in Java.

Examples

// 1. Final Class
final class ImmutableClass {
    // Cannot be inherited
}

class Parent {
    // 2. Final Method
    public final void strictMethod() {
        System.out.println("Cannot be overridden");
    }
}

public class FinalExample extends Parent {
    // public void strictMethod() {} // COMPILE ERROR!
    
    public static void main(String[] args) {
        // 3. Final Variable
        final int MAX_USERS = 100;
        // MAX_USERS = 200; // COMPILE ERROR!
        
        final StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World"); // ALLOWED! The internal state changed.
        // sb = new StringBuilder(); // COMPILE ERROR! Cannot reassign reference.
    }
}

Interview Questions

Q: What is the difference between final, finally, and finalize()?
A: - final is a keyword used to apply restrictions on variables, methods, and classes.

  • finally is a block used in exception handling (try-catch-finally) to ensure a block of code is executed regardless of whether an exception occurs.
  • finalize() is a deprecated method of the Object class, formerly used by the Garbage Collector before an object is destroyed.

Q: Can a final variable be initialized in a constructor?
A: Yes. A final instance variable (that is not initialized at the point of declaration) is called a blank final variable. It must be initialized within every constructor of the class; otherwise, it will not compile.