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);
  1. A. It prints null and then throws NullPointerException
  2. B. It prints null null
  3. C. It throws NullPointerException before printing anything
  4. 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

Exams that ask this topic