Original source: http://hi.baidu.com/eduask%C9%BD%C8%AA/blog/item/227bf4d81c71ebf538012f53.html
package com.test; public class Test { public static void main (String []args) {Integer a = 100; // If you use new here, the = = value must be false Integer B = 100; System.out.println (a ==b); // true Integer c = 150; Integer d = 150; System.out.println (c ==d); // false }}
What is the reason for this?
1. Java at compile time Integer a = 100; is translated as Integer a = integer.valueof (100);
2. Comparison is still a comparison of objects
3. In the JDK source code
Public Static Integer valueOf (int i) { finalint offset =N; if//return// match value range, enter also create good static intergercache,i+ The value of offset indicates the value of the drop in the cache array } returnnew// when the value range of 128 127 is not met. Remember to use: New, open up the memory space, not belong to the Intergercache management area
and
Private Static classIntegercache {PrivateIntegercache () {}Static FinalInteger cache[] =Newinteger[-(-128) + 127 + 1];//Open 128 to 127 of the memory area. There's a 0 position. Static{ for(inti = 0; i < cache.length; i++) Cache[i]=NewInteger (i-128);//assigns a value to each object in an array of memory areas }}
This is java. In order to improve efficiency, the integer object between -128--127 is initialized, so the assignment is the same object within this range.
Add one more word.
Integer a = 100;
a++;
This way, a++ is a new object is created, not a previous object.
Public Static void Main (String []args) { = +; = A; // at this point the B pointer to the heap address of value 100 is the heap address of a, a==b established a++; At this point the value of a is changed to a heap address where the 101,a pointer points to 101. and b still pointsto the System.out.println (a==b); false }
Range of JAVA integer values