Assigning a null value to an int

That code will give a NullPointerException when you run it. It's basically equivalent to:

Integer a = null;
int b = a.intValue();

... which makes it clearer that it will indeed fail.

You're not really assigning a null value to an int - you're trying and failing.

It's fine to use null as a value for an Integer; indeed often Integer is used instead of int precisely as a "nullable equivalent`.


It is not possible. You will get NullPointerException


That will throw a NullPointerException.

The reason for this is that you're relying on auto-unboxing of the Integer value to an int primitive type. Java does this by internally calling .intValue() on the Object, which is null.

As to either it's a good practice or not... I would advise against doing so, unless the code is only used by you and you're extremely well behaved, making sure that you only assign the return value of such method to Integer values, not int.

If your code ends up in a lib used by others, it's not safe, and I would rather explicitly throw an Exception, well documented, and allow for defensive coding on the caller's part.


Funny thing with Java tenerary operator ?: (using 8u151 on OSX)

If you do

Integer x = map == null ? 0 : map.get ( key );

which seems fine and compact and all, then you get an npe!!! if

map.get ( key )

is a null. So I had to split that and it worked fine.

Tags:

Java