ProgrammingVery hardTCS NQT Digital · Accenture Advanced

What happens when this runs?

What happens when this runs?
Integer n = null;
boolean flag = false;
Integer r = flag ? 1 : n;
System.out.print(r);
  1. A. Prints null
  2. B. Prints 1
  3. C. Throws NullPointerException
  4. D. Compile error

Correct answer: C. Throws NullPointerException

With operands int and Integer the conditional has type int, so the chosen operand n is unboxed, and unboxing null throws NullPointerException.

More OOP with C++ and Java questions

Exams that ask this topic