Today, I looked at the source of the integer:
Public StaticInteger valueOf (String s)throwsNumberFormatException {returnInteger.valueof (parseint (S, 10)); } /*** Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) As required by JLS. * * The cache is initialized on first usage. The size of the cache * May is controlled by the {@code-xx:autoboxcachemax=<size>} option. * During VM initialization, Java.lang.Integer.IntegerCache.high property * is set and saved in the private system Properties in the * Sun.misc.VM class. */ Private Static classIntegercache {Static Final intLow =-128; Static Final intHigh ; Static FinalInteger cache[]; Static { //High value is configured by property intH = 127; String Integercachehighpropvalue=Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); if(Integercachehighpropvalue! =NULL) { Try { inti =parseint (Integercachehighpropvalue); I= Math.max (i, 127); //Maximum array size is Integer.max_valueh = math.min (i, Integer.max_value-(-low)-1); } Catch(NumberFormatException nfe) {//If The property cannot is parsed into an int, ignore it.}} High=h; Cache=Newinteger[(high-low) + 1]; intj =Low ; for(intk = 0; K < Cache.length; k++) Cache[k]=NewInteger (j + +); //range [ -128, 127] must be interned (JLS7 5.1.7) assertIntegercache.high >= 127; } PrivateIntegercache () {}}/*** Returns an {@codeInteger} instance representing the specified * {@codeint} value. If a new {@codeInteger} instance is isn't * required, this method should generally being used in preference to * the constructor {@link#Integer (int)}, as this method was likely * to yield significantly better space and time performance by * Cach ing frequently requested values. * This method would always have the cache values in the range-128 to 127, * inclusive, and may caches other values outside of this range. * * @paramI an {@codeint} value. * @returnAn {@codeInteger} instance representing {@codei}. *@since1.5*/ Public StaticInteger ValueOf (inti) {if(I >= integercache.low && i <=Integercache.high)returnIntegercache.cache[i + (-Integercache.low)]; return NewInteger (i); }
After the virtual device is started, integer instantiates -128--127 integers in advance, regardless of how many integer.valueof are created with the same object.
Test:
Integer int1 = integer.valueof ("120");
Integer Int2 = integer.valueof ("120");
System.out.println (int1 = = Int2);
The result above is true, because within the range of the integer cache, all references are the same object
Integer int1 = integer.valueof ("190");
Integer Int2 = integer.valueof ("190");
System.out.println (int1 = = Int2);
The result above is false because the integer cache range is exceeded and a new integer object is eventually
Learn about the cache class for integers integercache