This is explained in the documentation right next to this code sample:
Note that boxing of numbers does not necessarily preserve identity
Basically, using the nullable Int?
type forces the compiler to use the boxed Integer
type for those variables in the generated bytecode instead of the primitive int
. So the code sample translates to this Java code:
int a = 10000;
Integer boxedA = Integer.valueOf(a);
Integer anotherBoxedA = Integer.valueOf(a);
System.out.print(boxedA == anotherBoxedA);
This, of course, prints false
, since two different Integer
instances have been created by the two Integer.valueOf
calls. Thought the JVM has caching for the instances created by Integer.valueOf
calls, it only works between -128 and 127 - if you run the code with a
having a value in that range, both comparisons will indeed return true
.