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");
        }
    }
}
  1. A. RE
  2. B. CCE
  3. C. Compile-time error: cannot cast String to Integer
  4. 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

Exams that ask this topic