Java basic training: the difference between Integer and int

  1. Int is a basic data type, and Integer is a reference data type;
  2. The default value of int is 0, and the default value of Integer is null;
  3. The int type directly stores the value. Integer needs to instantiate the object and point to the address of the object.
  4. In fact, there are some detailed differences between them: as follows
    public static void main(String[] args) {
        Integer a = new Integer(1);
        Integer b = new Integer(1);

        int c = 1;
        int d = 1;

        Integer e = 1;
        Integer f = 1;
        
        Integer g = 130;
        Integer h = 130;
        
        Integer i = new Integer(130);
        int j = 130;
    }

 

  • a == b? Not equal, the addresses of the two new objects are not the same.
  • Is c == d? The values ​​of all basic data types must be equal.
  • The key question now is e == f? Is g == h?

The answer is: e == f; g != h. Why does this happen? Because Integer g = 130 will be compiled into Integer.valueOf(130) when ava is compiling, which can be seen by decompiling the class file. From the Integer source code, it can be concluded that the Integer.valueOf() method will cache the Integer between the value -128~127, and will not renew one, so e==f; when the value two is greater than 127 or less than- At 128, a new one will be renewed, so g != h.
The valueOf method of Integer is as follows:
    public static Integer valueOf(int i) {          //IntegerCache.low == -128; IntegerCache.high == 127          //When the value is greater than -128 and less than 127, cache; otherwise, renew one.         if (i >= IntegerCache.low && i <= IntegerCache.high)             return IntegerCache.cache[i + (-IntegerCache.low)];         return new Integer(i);     }





  • Is c == e, i == j?

The answers are all equal. Because when the package class is compared with the basic data type, Java will automatically unbox it and compare whether the values ​​are equal.
In summary, we can draw several conclusions:
1. They are all encapsulated classes, which are all new, and they are definitely not equal. Because the memory address of the object is different.
2. They are all encapsulated classes and are not new. If the value is between -128 and 127, it is equal, otherwise it is not.
3. If the package class is compared with the basic type, as long as the value is equal, it is equal, otherwise it is not equal. Because there is an automatic unboxing operation when the package class and the basic data type are compared.
4. They are all basic data types. If the values ​​are equal, they are equal; otherwise they are not equal

Guess you like

Origin blog.csdn.net/orzMrXu/article/details/104845704