Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Autoboxing can automatically wrap the primitive type to the corresponding wrapper object, which can be convenient in many cases and avoid clutters in your own code. But you should always be careful about this process, especially when comparison.

Section 5.1.7 of JLS 3rd Ed can explain this problem clearly:

"If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2."

Consider the following code:

...

Code Block
true
false
false
true

Section 5.1.7 of JLS 3rd Ed can explain this problem clearly:

...

Here the cache in the Integer class can make class can only make the number from -127 to 128 refer to the same object, which clearly explains the result of above code.  In case of making such mistakes, when we need to do some comparisons of these wrapper class, we should use equal instead "==" (see EXP03-J for details):

...