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);
- A. It prints null, and then prints null again
- B. It prints null, and then prints 0
- C. It throws NullPointerException already at r1
- 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
- What is printed? java System.out.print(Math.abs(Integer.MINVALUE) + " "); System.out.print(Integer.MAXVALUE + 1 == Integer.MINVALUE);
- What is printed? java System.out.print((-7 / 2 == -3) + " " + (-7 % 2 == 1) + " " + (Math.floorMod(-7, 2) == 1) + " " + (7 % -2 == 1));
- Which line fails to compile? java byte b = 10; b += 5; // line 1 b++; // line 2 b = b + 1; // line 3 b = 10 + 20; // line 4
- What is printed? java int i = 0, j = 0; boolean p = (i++ > 0) & (i++ > 0); boolean q = (j++ > 0) && (j++ > 0); System.out.print(i + " " +…
- What is printed? java class P { private void f() { System.out.print("P"); } void call() { f(); } } class C extends P { void f() {…
- What is printed? java class P { static String s() { return "S"; } } // in main: P p = null; System.out.print(p.s());