WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Intermediate · question 37 of 100

What is a final keyword in Java? How is it used?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, the final keyword is used to indicate that a variable, method, or class cannot be changed or overridden. Once a variable or reference is marked as final, its value cannot be modified. Similarly, once a method or class is marked as final, it cannot be overridden by any subclasses.

Here are some examples of how the final keyword can be used:

public class MyClass {
    public static final int MAX\_VALUE = 100;
    
    public void doSomething(final int x) {
        final int y = 10;
        // MAX\_VALUE = 200; // error: cannot modify final variable
        // x = 20; // error: cannot modify final parameter
        // y = 30; // error: cannot modify final local variable
    }
}

In this example, we declare a final variable MAX_VALUE that cannot be modified. We also declare a final parameter x and a final local variable y, both of which cannot be modified within the method.

public class MyClass {
    public final void doSomething() {
        // method implementation
    }
}
    
public class MySubclass extends MyClass {
        // error: cannot override final method
        // public void doSomething() {
        // // method implementation
    // }
}

In this example, we declare a final method doSomething() in the MyClass class. This method cannot be overridden by any subclasses, as attempting to do so will result in a compilation error.

public final class MyClass {
    // class implementation
}

public class MySubclass extends MyClass {
    // error: cannot inherit from final class
}

In this example, we declare a final class MyClass that cannot be subclassed. Any attempt to subclass MyClass will result in a compilation error.

In summary, the final keyword is used to indicate that a variable, method, or class cannot be changed or overridden. It is commonly used for constants, immutable objects, and to prevent unintended changes to method or class behavior.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics