Interview: The difference between int and Integer

Difference between int and Integer

1. Integer is a wrapper class for int, and int is a basic data type of java. 
2. Integer variables must be instantiated before they can be used, and int variables do not need to be used. 
3. Integer is actually a reference to an object. In fact, a pointer is generated to point to this object; while int directly stores the data value 
4, the default value of Integer is null, and the default value of int is 0

Extension: 
Comparison of Integer and int 
1. Since the Integer variable is actually a reference to an Integer object, the two Integer variables generated by new are always unequal (because new generates two objects whose memory addresses are different).

Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false

2. When comparing an Integer variable with an int variable, as long as the values ​​of the two variables are equal, the result is true (because when the wrapper class Integer is compared with the basic data type int, java will automatically unpack it as int, and then compare, In fact, it becomes a comparison of two int variables)

Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true

3. When comparing an Integer variable not generated by new and a variable generated by new Integer(), the result is false. (Because the Integer variable generated by non-new points to the object in the java constant pool, and the variable generated by new Integer() points to the newly created object in the heap, the addresses of the two in memory are different)

Integer i = new Integer(100);
Integer j = 100;
System.out.print(i == j); //false

4. For two non-new generated Integer objects, when comparing, if the value of the two variables is between -128 and 127, the comparison result is true, and if the value of the two variables is not in this interval, the comparison result false

Integer i = 100;
Integer j = 100;
System.out.print(i == j); //true
Integer i = 128;
Integer j = 128;
System.out.print(i == j); //false

For the reason of item 4: 
When java compiles Integer i = 100;, it will be translated into Integer i = Integer.valueOf(100);, and the definition of valueOf of Integer type in the java API is as follows:

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);
}

java对于-128到127之间的数,会进行缓存,Integer i = 127时,会将127进行缓存,下次再写Integer j = 127时,就会直接从缓存中取,就不会new了

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324787066&siteId=291194637