ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
Object o = "text";
try {
Integer n = (Integer) o;
System.out.print(n);
} catch (ClassCastException e) {
System.out.print("CCE");
} catch (RuntimeException e) {
System.out.print("RE");
}
}
}- A. RE
- B. CCE
- C. Compile-time error: cannot cast String to Integer
- D. text
Correct answer: B. CCE
o actually holds a String at runtime, so casting it to Integer fails at runtime with a ClassCastException. ClassCastException is caught by the first matching catch clause, catch (ClassCastException e), printing CCE; the compiler allows the cast syntactically since both are reference types, deferring the check to runtime.
More OOP with C++ and Java questions
- What is printed? java public class Main { static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { return…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { Map<String, Integer> m = new…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abc"); try {…
- What is printed? java class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } B(int x) { this()…
- What happens when this is compiled? java class A { A(int x) { System.out.print("A(int) "); } } class B extends A { B() {…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "~A"; } }; struct B { A a; B() { cout << "B"; } ~B() { cout << "~B"; }…