Quiz About Java Final Keyword
Quiz About Java Final Keyword
Question 1
Discuss it
Question 1 ‒ Explanation
See final in Java.
Question 2
Java
Trending Now Data Structures Algorithms System Design Foundational Courses Data Science Practice Problem Python Machine L
class Main {
public static void main(String args[]){
final int i;
i = 20;
System.out.println(i);
}
}
20
Compiler Error
Garbage value
Discuss it
Question 2 ‒ Explanation
There is no error in the program. final variables can be assigned value only once. In the above program, i is ass
igned a value as 20, so 20 is printed.
Question 3
Java
class Main {
public static void main(String args[]){
final int i;
i = 20;
i = 30;
System.out.println(i);
}
}
30
Compiler Error
Garbage value
Discuss it
Question 3 ‒ Explanation
i is assigned a value twice. Final variables can be assigned values only one. Following is the compiler error "Mai
n.java:5: error: variable i might already have been assigned"
Question 4
Java
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();
}
}
Derived::show() called
Base::show() called
Compiler Error
Exception
Discuss it
Question 4 ‒ Explanation
compiler error: show() in Derived cannot override show() in Base