ProgrammingVery hardProduct company interview · GATE level
What happens when this code runs?
What happens when this code runs?
Integer n = null; boolean flag = true; Integer a = flag ? n : Integer.valueOf(0); System.out.print(a + " "); Integer b = flag ? n : 0; System.out.print(b);
- A. It prints null and then throws NullPointerException
- B. It prints null null
- C. It throws NullPointerException before printing anything
- D. It prints null 0
Correct answer: A. It prints null and then throws NullPointerException
When both operands of ?: are Integer, the result type is Integer, so a is simply null and 'null ' is printed. When one operand is Integer and the other is the int 0, the conditional's type is int: the chosen operand n is unboxed, and unboxing null throws NullPointerException - even though the result would be boxed back into an Integer variable.
More OOP with C++ and Java questions
- Which lines fail to compile? java short s = 1; s = s + 1; // L1 s += 1; // L2 char c = 'A'; c++; // L3 final int k = 10; byte b1 = k; //…
- Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.) java // A try…
- What is printed? java class R implements AutoCloseable { public void close() { throw new IllegalStateException("close"); } } // in main…
- What is printed? java class T { static int a = T.b + 1; static int b = 5; static int c = b + 1; } // in main: System.out.print(T.a + " " +…
- What is printed? java class K { static final int C = 10; static final Integer D = 20; static { System.out.print("K "); } } // in main…
- Which lines fail to compile? java interface I { static String id() { return "I"; } default String name() { return "N"; } } class C…