0

Why does the code below throw null pointer exception? I would expect the equivalence to be simply false. Can someone explain what happens under the hood and the reason for this design decision?

Integer i = null;
System.out.println(i == 10);  // Throws a null pointer exception
CEGRD
  • 7,787
  • 5
  • 25
  • 35
  • 1
    You might want to some research into "auto boxing" in Java – MadProgrammer Jan 22 '18 at 23:24
  • Well, `Integer` is just an object. Any object reference can throw NPE in Java: `Object i = null; System.out.println( i == 10 );` – markspace Jan 22 '18 at 23:29
  • @MadProgrammer , how would you explain the NPE given that System.err.println(i == new Integer(10)); prints false ? – David Soroko Jan 22 '18 at 23:42
  • @DavidSoroko Read the duplicate link `Integer == Integer` is now comparing object references (as apposed to `int == int` which will compare primitive values), since they aren't the same reference, the comparison is `false` – MadProgrammer Jan 22 '18 at 23:45
  • Well yes, and regarding the OPs question... – David Soroko Jan 22 '18 at 23:49
  • As the relevant links in the referenced answer is broken, have a look at this: https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.21.1 The NPE happens due to unboxing of i – David Soroko Jan 23 '18 at 00:01

0 Answers0