About the comparison of integers and int
1. Because the integer variable is actually a reference to an integer object, the two integer variables generated by new are never equal (because new generates two objects with different memory addresses).
Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false
2, the integer variable and the int variable comparison, as long as the value of two variables is equal, the result is true (because the wrapper class integer and the base data type int Compare, Java will automatically unpack to int, then compare, actually become the comparison of two int variable)
Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true
3. The result is false when the non-new generated integer variable is compared to the variable generated by the new Integer (). (Because a non-new integer variable points to an object in a Java constant pool, the new Integer () generates a variable that points to the new object in the heap, and the address in memory is different)
Integer i = new Integer(100);
Integer j = 100;
System.out.print(i == j); //false
4, for two non-new integer objects, when compared, if the value of two variables between the interval-128 to 127, then the comparison result is true, if the value of two variable is not in this interval, the comparison result is 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 article 4th:
Java is translated into integer i = integer.valueof (100) when compiling integer i = 100, while the Java API defines the valueOf of the integer type 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 for the number between 128 to 127, will be cached, the integer i = 127, 127 will be cached, the next time you write the Integer j = 127, will be taken directly from the cache, will not be new
The Integer in Java