Back to Study Material Java

Final Keyword in Java

The final keyword in Java is a non-access modifier that signals an intent that something should not be changed after its initial assignment or definition. ...

Final Keyword in Java

Locking Down Variables, Methods, and Classes

The final keyword in Java is a non-access modifier that signals an intent that something should not be changed after its initial assignment or definition. It can be applied to three different contexts—variables, methods, and classes—and the exact meaning shifts slightly in each context. Using final is both a safety mechanism and a form of documentation: it tells other developers "this was designed to never change."

Final Variables: Constants A final variable can be assigned only once. For primitives, the value itself is fixed. For objects, the reference is fixed—you cannot point the variable at a different object—but the object's internal fields can still change unless they are also final. The combination of static and final is the standard idiom for class-level constants: public static final double PI = 3.14159. By convention, constants are named in ALL_CAPS with underscores.

Final Methods: Preventing Override A method declared final cannot be overridden by subclasses. This is used when the implementation must remain exactly as written for correctness or security reasons. For example, a banking transaction method might be final to prevent a subclass from accidentally or maliciously changing the calculation logic. The JVM can also optimize final methods more aggressively because it knows the implementation will never change at runtime.

Final Classes: Preventing Extension A final class cannot be subclassed at all. java.lang.String is the most famous example—it is final because immutability guarantees depend on no subclass being able to add mutable state. Other examples include Integer, Double, and all the primitive wrapper classes. When you mark a class final you are saying the design is complete and extension would break the intended contract.

Code Example: final class ImmutablePoint { final int x; final int y; ImmutablePoint(int x, int y) { this.x = x; this.y = y; } } ImmutablePoint p = new ImmutablePoint(3, 4); // p.x = 10; // compile error - final field

Interview Tip: A subtle exam question: can a final method be overloaded? Yes, absolutely. Overloading creates a new method with a different parameter list; it does not modify the existing method. Only overriding—providing a new implementation for the same signature—is prohibited. Distinguishing overloading from overriding in the context of final is a reliable differentiator between candidates.