Smart Tech for a better Web
Today I was preparing some slides for my upcoming SCJP training. I stumbled across something really odd in Java. Lets say you have this code:
It has been said, due to the autoboxing feature of Java >5 Wrapper-classes can be compared with ==, because they are unboxed and compared. Output for number one is:
You would guess option two prints out the same, but it does not. The output is:
Since you have assigned objects yourself, they are not ==. Only when you let the JVM instance the Wrapper with autoboxing, this feature works.
Isn’t this very unrealiable? You cannot trust Integer == Integer to work in all cases. The developer must follow strict conventions. Nasty, nasty…
equals for comparing Object and == for primitives is still the best solution.