What is a final keyword in Java?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex OOP Concepts topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
The final keyword in Java prevents modification, depending on what it's applied to: (1) Final variable (constant): can only be assigned once — cannot be reassigned: final int MAX_SIZE = 100; MAX_SIZE = 200; // Compile error! // Instance final (must be initialized in constructor): class Circle { private final double radius; public Circle(double radius) { this.radius = radius; } // radius can never change after construction }; (2) Final method: cannot be overridden by subclasses: class BankAccount { final void close() { // Security: can't override this critical operation this.status = "CLOSED"; saveToAuditLog(); } } class SavingsAccount extends BankAccount { // Can't override close() -- compile error if tried }; (3) Final class: cannot be extended/subclassed: final class ImmutablePoint { private final int x, y; public ImmutablePoint(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } // No setters! } // class ExtendedPoint extends ImmutablePoint {} // Error!. Examples: String, Integer, all wrapper classes in Java are final. Final fields for immutability: a class is truly immutable if all fields are final AND the referenced objects are also immutable (deep immutability). Immutable objects are thread-safe by design. Effectively final (Java 8+): local variables used in lambdas must be final or effectively final (never reassigned): int count = 0; // Effectively final list.forEach(item -> System.out.println(count)); // OK count++; // Now NOT effectively final -- lambda use would fail.
Pro Tip
This topic has OOP Concepts-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.