Java final keyword

Question 1

What is the use of final keyword in Java?

Cross

When a class is made final, a subclass of it can not be created.

Cross

When a method is final, it can not be overridden.

Cross

When a variable is final, it can be assigned value only once.

Tick

All of the above



Question 1-Explanation: 
Question 2
Output of following Java program
class Main {
 public static void main(String args[]){
   final int i;
   i = 20;
   System.out.println(i);
 }
}
Tick
20
Cross
Compiler Error
Cross
0
Cross
Garbage value


Question 2-Explanation: 
There is no error in the program. final variables can be assigned value only once. In the above program, i is assigned a value as 20, so 20 is printed.
Question 3
class Main {
 public static void main(String args[]){
    final int i;
    i = 20;
    i = 30;
    System.out.println(i);
 }
}
Cross
30
Tick
Compiler Error
Cross
Garbage value
Cross
0


Question 3-Explanation: 
i is assigned a value twice. Final variables can be assigned values only one. Following is the compiler error \"Main.java:5: error: variable i might already have been assigned\"
Question 4
class Base {
  public final void show() {
       System.out.println("Base::show() called");
    }
}
class Derived extends Base {
    public void show() {  
       System.out.println("Derived::show() called");
    }
}
public class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}
Cross
Derived::show() called
Cross
Base::show() called
Tick
Compiler Error
Cross
Exception


Question 4-Explanation: 
compiler error: show() in Derived cannot override show() in Base
There are 4 questions to complete.

  • Last Updated : 25 Oct, 2021

Share your thoughts in the comments
Similar Reads