I'm comparing object references (pointers) not the value boxed by the object (what the pointer points to).
For performance reasons boxed Short objects are interned when they represent values in the range -127 to +128 so for 42 the pointers will point to the same interned object after 42 is autoboxed to a Short. Whereas 1042 is outside this interning range and the autoboxing creates two distinct objects with different pointers.
It's very simple but (a) non-obvious if you don't know about it and (b) rather wordy when I spell it out like this :)
In general in Java you want obj.equals(other) when dealing with objects and == only with primitives, but autoboxing/unboxing can cause confusion about which one is dealing with.
In other other words, the surprise ought to be that w == x is true, not that y == z is false!
I'm comparing object references (pointers) not the value boxed by the object (what the pointer points to).
For performance reasons boxed Short objects are interned when they represent values in the range -127 to +128 so for 42 the pointers will point to the same interned object after 42 is autoboxed to a Short. Whereas 1042 is outside this interning range and the autoboxing creates two distinct objects with different pointers.
It's very simple but (a) non-obvious if you don't know about it and (b) rather wordy when I spell it out like this :)
In general in Java you want obj.equals(other) when dealing with objects and == only with primitives, but autoboxing/unboxing can cause confusion about which one is dealing with.
In other other words, the surprise ought to be that w == x is true, not that y == z is false!