Java tutorial -- difference between int and Integer: javaintinteger
First, let's talk about the difference between int and Integer:
The following is an example:
1 package syswar.cc; 2 3 public class IntegerCompare { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Integer a1 = 2; 8 Integer a2 = 2; 9 10 Integer b1 = 150;11 Integer b2 = 150;12 13 Integer c1 = new Integer(2);14 Integer c2 = new Integer(2);15 16 Integer d1 = new Integer(150);17 Integer d2 = new Integer(150);18 19 System.out.println("a1==a2?" + (a1==a2));20 System.out.println("b1==b2?" + (b1==b2));21 System.out.println("c1==c2?" + (c1==c2));22 System.out.println("d1==d2?" + (d1==d2));23 }24 25 }
Running result:
a1==a2?trueb1==b2?falsec1==c2?falsed1==d2?false
Why is this result? We first compare the two groups a and B. During Integer initialization, the Integer object data is cached. The int value corresponding to these Integer objects is in the byte range, that is, [-128,127].
When an Integer is directly assigned an int value, if the value range is [-128,127], the Integer directly retrieves the Integer object from the cache. Therefore, when the int value directly assigned is in [-128,127], the Integer object is the same object.
The Integer object obtained through the new method is directly allocated from the heap. Therefore, no matter how many int values are, the result of = is false.