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

Core Java · Basic · question 16 of 100

What is a final keyword in Java?

📕 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 modified or extended.

When applied to a variable, the final keyword indicates that the variable’s value cannot be changed once it has been initialized. This makes the variable a constant. Here’s an example:

public class Main {
    public static void main(String[] args) {
        final int MAX_VALUE = 10;
        // MAX_VALUE = 20; 
        // Compilation error: cannot assign a value to final variable
        System.out.println(MAX_VALUE);
    }
}

In this example, we declare a constant MAX_VALUE and initialize it with the value 10. Since MAX_VALUE is declared as final, we cannot change its value later in the program. If we try to assign a new value to MAX_VALUE, we get a compilation error.

When applied to a method, the final keyword indicates that the method cannot be overridden by subclasses. Here’s an example:

public class Animal {
    public final void makeSound() {
        System.out.println("Animal is making a sound");
    }
}

public class Dog extends Animal {
    // Attempt to override makeSound method 
    // will result in a compilation error
}

In this example, the makeSound method of the Animal class is declared as final. This means that it cannot be overridden by subclasses such as the Dog class. If we attempt to override the makeSound method in the Dog class, we get a compilation error.

When applied to a class, the final keyword indicates that the class cannot be subclassed. Here’s an example:

public final class MyClass {
    // Class definition goes here
}

// Attempt to extend MyClass will result in a compilation error
// public class MySubclass extends MyClass {
// }

In this example, the MyClass class is declared as final, which means that it cannot be subclassed. If we attempt to define a subclass of MyClass called MySubclass, we get a compilation error.

In general, the final keyword is used to indicate that something cannot be modified or extended, which can help prevent bugs and improve code safety. It is commonly used to define constants, prevent method overrides, and prevent class inheritance.

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