public class Demo {
public static void main(String[] args) {
Integer a = 1000, b = 1000;
Integer c = 100, d = 100;
int e = 100;
Integer f = new Integer(10);
Integer g = new Integer(10);
System.out.println(a == b);// false
System.out.println(c == d);// true
System.out.println(e == d);// true
System.out.println(f == g);// false}}Copy the code
The compiled:
public class Demo {
public static void main(String[] args) {
Integer a = Integer.valueOf(1000); Integer b = Integer.valueOf(1000);
Integer c = Integer.valueOf(100); Integer d = Integer.valueOf(100);
int e = 100;
Integer f = new Integer(10);
Integer g = new Integer(10); System.out.println(a == b); System.out.println(c == d); System.out.println(e == d.intValue()); System.out.println(f == g); }}Copy the code
The secret:
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);
}
Copy the code
When we declare an Integer c = 100; At this time, automatic packing operation will be carried out. To put it more simply, it converts the basic data type to an Integer object, which is exactly what valueOf calls. As you can see, Integer caches -128 to 127.
When the Integer object is new, it is not cached, so the result is false.