The JDK source code shows the optimizations in integer. valueof (INT:
Public static integer valueof (int I) {<br/> final int offset = 128; <br/> if (I >=- 128 & I <= 127) {// must cache <br/> return integercache. cache [I + offset]; <br/>}< br/> return New INTEGER (I ); <br/>}</P> <p> Private Static class integercache {<br/> private integercache () {}</P> <p> static final integer cache [] = new integer [-(-128) + 127 + 1]; <br/> static {<br/> for (INT I = 0; I <cache. length; I ++) <br/> cache = new INTEGER (I-128); <br/>}< br/>}
SlaveSource codeYou can see that valueof is-128 ~ 127 these 256 values are cached (integercache), if the int value range is-128 ~ 127. When valueof (INT) is used, it will directly return the integercache cache to you.
Public static void main (string [] ARGs) {<br/> integer a = 10; <br/> integer B = 10; <br/> system. out. println (A = B); <br/> integer c = new INTEGER (10); <br/> integer d = new INTEGER (10); <br/> system. out. println (C = D); <br/>}
The result is:
True
False
Because: During Java compilation, integer a = 100; is translated into-> integer a = integer. valueof (100);, so a and B get a cache object, and it is the same! C and D are two new objects, So C is not equal to D.