Explain the final keyword in Java.

The final keyword in Java is used to restrict modification. It can be applied to variables, methods, and classes to prevent changes after declaration, helping create secure and predictable code.

Key Points: • A final variable can be assigned a value only once and cannot be reassigned. • A final method cannot be overridden by a subclass. • A final class cannot be extended or inherited. • The final keyword is commonly used to define constants and prevent unintended modifications. • It improves code reliability by enforcing design constraints.

Example: The String class in Java is declared as final, which prevents other classes from inheriting and modifying its behavior.

Code Example:

final class Vehicle {
}

class Employee {

    final int ID = 101;

    final void display() {
        System.out.println("Employee Details");
    }
}

Interview Tip: A concise interview answer is:

"The final keyword is used to restrict changes in Java. A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be inherited."