For example:
int anInt = null;
fails at compile time but
public static void main(String[] args) {
for (int i = 0; i < 10;
Boxing partially hides the distinction between primitives and corresponding wrapper objects, but it doesn't remove it.
There are two distinctions which are not changed by boxing:
Occasionally, these differences can cause problems when using boxing.
Some points to remember :
NullPointerException
.==
and equals
must be done with care. In the first case, the compiler knows that you're trying to unbox a compile-time constant of null
.
In the second case, the type of the conditional expression is Integer
, so you're effectively writing:
Integer tmp = new Random().nextBoolean() ? 1 : null;
return (int) tmp;
... so the unboxing isn't happening on a constant expression, and the compiler will allow it.
If you changed it to force the conditional expression to be of type int
by unboxing there, it would fail:
// Compile-time failure
return new Random().nextBoolean() ? 1 : (int) null;
You can't assign null to an int
int anInt = null;
Java allows this since you are not assigning null to an int
System.out.println("" + getSomeVal()); //null was just converted to a srting and was printed
If you perform this, you can get the error
int anInt = getSomeVal();