-3

What is the value of i when you execute the code below and why?

int i = (Integer)null;
Gustavo
  • 1,332
  • 2
  • 16
  • 39
  • I already did. It's the why that interests me most, an may be useful to other people. – Gustavo Dec 18 '18 at 15:21
  • 1
    @Gustavo "why" is "because it was designed like that", and it's documented in the relevant JLS. – BackSlash Dec 18 '18 at 15:22
  • Ok. But comments is not the right place to answer. – Gustavo Dec 18 '18 at 15:22
  • Null gets correctly cast to an Integer. Java attempts to unbox the integer into a primitive int so that it may store it in the variable, effectively calling `null.intValue()` which results in a NPE. – Michael Dec 18 '18 at 15:28
  • Guys, the section below is the right place to answer, not here. Also, this is not a duplicate, because it's not about casting, but about unboxing. – Gustavo Dec 18 '18 at 15:32
  • 1
    Duplicate of https://stackoverflow.com/questions/2382058/unboxing-null-object-to-primitive-type-results-in-nullpointerexception-fine , should probably be updated – BackSlash Dec 18 '18 at 15:36

1 Answers1

4

See jls5.1.8:

At run time, unboxing conversion proceeds as follows:

...

If r is null, unboxing conversion throws a NullPointerException

xingbin
  • 27,410
  • 9
  • 53
  • 103