Versions Compared

Key

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

...

Code Block
public class TestWrapper2 {
 public static void main(String[] args) {
  
  Integer i1 = 100;
     Integer i2 = 100;
     Integer i3 = 1000;
     Integer i4 = 1000;
     System.out.println(i1==i2);
     System.out.println(i1!=i2);
     System.out.println(i3==i4);
     System.out.println(i3!=i4);
    
 }
}

This code uses "==" to compare 2 Integer object, from EXP03-J we can know that for "==" to return true for two object references, they must point to the same underlying object. So we can simply draw the conclusion that the results of using "==" operator in this code will be false. However, 

Output of this code 


Code Block
true
false
false
true

...

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

...

Code Block
public class TestWrapper2 {
 public static void main(String[] args) {
  
  Integer i1 = 100;
     Integer i2 = 100;
     Integer i3 = 1000;
     Integer i4 = 1000;
     System.out.println(i1.equals(i2));
     System.out.println(i3.equals(i4));    
 }
} 

Now, the results are all trues, as we expected. 

Noncompliant Code Example

...