12, the difference between the Integer and int

It is a wrapper class Ingeter int, int initial value is 0, the initial value Ingeter is null.

Package com.test;
 / ** 
 * 
 * @author Liu Ling 
 * 
 * / 
public  class TestInteger { 

    / ** 
     * @param args
      * / 
    public  static  void main (String [] args) {
         int I = 128 ; 
        Integer I2 = 128 ; 
        Integer I3 = new new Integer (128 );
         // Integer automatically unpacking of int, so as to true 
        System.out.println (I == I2); 
        System.out.println (I == I3);
        System.out.println ( "**************" ); 
        Integer i5 = 127; // Java at compile time, is translated into -> Integer i5 = Integer.valueOf (127 ); 
        Integer I6 = 127 ; 
        System.out.println (i5 == I6); // to true 
        / * Integer i5 = 128; 
        Integer I6 = 128; 
        System.out.println (i5 == I6); // to false 
* /         Integer II5 = new new Integer (127 ); 
        System.out.println (i5 == II5); // to false 
        Integer i7 = new new Integer (128 ); 
        Integer I8 =new Integer(123);
        System.out.println(i7 == i8);  //false
    }

}

First, row 17 and row 18 are output to true, because the ratio of int Integer and unboxing automatically (JDK1.5 above).
In fact, at compile java Integer when i5 = 127, and it is translated into -> Integer i5 = Integer.valueOf (127 ); so the key is to look at valueOf () function of. Just look valueOf () function of the source code will understand. JDK source such functional valueOf:

public static Integer valueOf(int i) {
      assert IntegerCache.high >= 127;
         if (i >= IntegerCache.low && i <= IntegerCache.high)
             return IntegerCache.cache[i + (-IntegerCache.low)];
         return new Integer(i);
     }

When we look at the source code will be appreciated that for a number between -128 and 127, can be cached when Integer i5 = 127, 127 will be cached next write Integer i6 = 127, will be taken directly from the cache would not the new. So the result on line 22 is true, while 25 behavioral false.

For the 27 lines and 30 lines, because the object is not the same, it is false.

Summarized as follows:

① In any case, Integer with a new Integer will not be equal. Will not go through the process of unpacking, i3 reference point to heap
② two are non-new out of the Integer, if the number is between -128 and 127, it is true, otherwise false
the Java compiler Integer i2 = 128 at the time, was translation into -> Integer i2 = Integer.valueOf (128 ); and valueOf () function will have a number between -128 and 127 caching
③ out of the two are new, are to false
④int and integer (whether new NO ) ratio, it is true, because Integer will automatically go unboxing to int ratio

Guess you like

Origin www.cnblogs.com/helenwq/p/11649699.html