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);
- A. Prints null
- B. Prints 1
- C. Throws NullPointerException
- 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
- What is printed? java byte b = 10; b += 120; System.out.print(b + " " + (b >>> 1));
- What is printed? java try { try { throw new Exception("1"); } finally { throw new RuntimeException("2"); } } catch (Exception e) {…
- What is printed? java class R implements AutoCloseable { String n; R(String n) { this.n = n; System.out.print("o" + n); } public void…
- What is printed? java class A {} class B extends A {} static void f(A a) { System.out.print("A"); } static void f(B b) {…
- What is printed? java class P { void f(Object o) { System.out.print("PO"); } } class C extends P { void f(String s) {…
- What happens? java static void f(String s) { System.out.print("S"); } static void f(Integer i) { System.out.print("I"); } // main: f(null);