ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement

What happens?

What happens?
boolean flag = true;
Integer none = null;
Integer r1 = flag ? null : 0;
System.out.print(r1);
Integer r2 = flag ? none : 0;
System.out.print(r2);
  1. A. It prints null, and then prints null again
  2. B. It prints null, and then prints 0
  3. C. It throws NullPointerException already at r1
  4. D. It prints null, then throws NullPointerException

Correct answer: D. It prints null, then throws NullPointerException

With the null literal and int, the conditional has type Integer, so r1 is simply null. With an Integer variable and int it is a numeric conditional of type int, so none is unboxed, which throws NullPointerException.

More OOP with C++ and Java questions

Exams that ask this topic