1

I was reading jls §5.1.7 and it says that there are 9 types of boxing, 9th one being Boxing From the null type to the null type

Then I read that Unboxing Conversion of null throws a NullPointerException. Ok that is obvious. Then why boxing of null does not throws a NullPointerExceptionand what is the use of boxing null value?

Vishrant
  • 15,456
  • 11
  • 71
  • 120
  • 1
    How can you have a primitive null? – Scary Wombat Mar 31 '14 at 07:13
  • I think its not about primitive null, we can have boxing for null type to null type as jls said. My question is what is the use of boxing null and why it does not throw NPE. – Vishrant Mar 31 '14 at 07:40
  • The answer is in the link you gave `This rule is necessary because the conditional operator (§15.25) applies boxing conversion to the types of its operands, and uses the result in further calculations.` – Scary Wombat Mar 31 '14 at 07:42
  • Because there is nothing to unbox. – user207421 Mar 31 '14 at 07:46

2 Answers2

1

Converting null to Integer does not throw NullPointerException because null is a valid value for any reference, e.g: Integer intObject = null; // fine

However, you cannot do this:

int intPrimitive = intObject; // not fine

Because when you try to convert an Integer to int the Integer.intValue() is called behind the scenes, but calling any method on a null reference throws NPE:

Object whatever = null;
whatever.anyMethod(); // always throws NPE

Because the reference points to null, not an actual object of the chosen type.

Bartek Maraszek
  • 1,404
  • 2
  • 14
  • 31
  • Not an answer. My question was for `Boxing` and `Unboxing` not reference type can have `null` values and primitive can not, I know this also have an answer http://stackoverflow.com/questions/19511616/why-java-does-not-allow-null-while-declaring-primitive-data-types – Vishrant Mar 31 '14 at 07:32
0

I think the doc you provide give the answer. "This rule is necessary because the conditional operator applies boxing conversion to the types of its operands, and uses the result in further calculations."

If one of second and third operands of ?: is not boolean or numeric expressions, then boxing may be used. For example, the type of true?1:2 is int, while the type of true?null:1 is Integer. In the second example, auto-boxing is employed. And in the run time, the second example's type will be null type because when boxing null type, a null type will be got.

locoyou
  • 1,697
  • 1
  • 15
  • 19