ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Object o = "hi"; String s = (String) o; Integer n = null; System.out.print((n instanceof Integer) + " " + (o instanceof Comparable) + " "); Integer bad = (Integer) o; System.out.print(bad);
- A. "true true " is printed, then ClassCastException is thrown
- B. Compile-time error at (Integer) o
- C. false true hi
- D. "false true " is printed, then ClassCastException is thrown
Correct answer: D. "false true " is printed, then ClassCastException is thrown
instanceof is false for null. A String is Comparable. Casting an Object reference to Integer compiles (it might be legal) but fails at run time because the object is a String.
More OOP with C++ and Java questions
- What is printed? java class A { static int v = 1; static int get() { return v; } } class B extends A { static int v = 2; } // in main…
- What happens when this code is compiled? java try { new java.io.FileReader("x.txt"); } catch (Exception e) { System.out.print("E"); }…
- What is printed? java // static method of the main class: static int f() { try { throw new RuntimeException("t"); } finally { return 7; }…
- What is printed? java try { try { throw new IllegalStateException("A"); } finally { throw new IllegalArgumentException("B"); } } catch…
- What is printed? java class K { static int v = 10 / Integer.parseInt("0"); } // in main: try { System.out.print(K.v); } catch…
- What is printed? java // static method of the main class: static void down() { down(); } // in main: try { down(); } catch (Exception e) {…