[Reprint] In Java why the variable 1000 = 1000 returns false, but 100=100 returns true?

Source: Internet
Author: User

PS: the title means = = Comparison between different variables that define the same content. The result of a direct comparison (1000 = = 1000) is true.

Run the following code:

    Integer a = +, B = +;         = = b)        ; = +, d = +;         = = d);

The result is:

false true

We know that if two references point to a different object, even if the object has the same content, the result they compare with = = is not equal (returns false).

According to reason, the result of the final return should also be false. But that is not the case.

This is the interesting place, if you look at the Integer.java class, you will find that the integer class has an inner class called Integercache, which caches all the integer objects between 128 and 127.

/*** Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as Requi Red by JLS.  * * The cache is initialized on first usage. The size of the cache * May is controlled by the-xx:autoboxcachemax=<size> option. * During VM initialization, Java.lang.Integer.IntegerCache.high property * May is set and saved in the private system prop Erties 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; //gets the high value in the configuration, the default maximum value is 127, but this value can also be customized to write in the configuration fileString Integercachehighpropvalue =Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); if(Integercachehighpropvalue! =NULL) {            inti =parseint (Integercachehighpropvalue); I= Math.max (i, 127); //Maximum array size is Integer.max_valueh = math.min (i, Integer.max_value-(-low)-1); } High=h; Cache=Newinteger[(high-low) + 1]; intj =Low ;  for(intk = 0; K < Cache.length; k++) Cache[k]=NewInteger (j + +);//Initialize the value of an array    }    PrivateIntegercache () {}}

So an integer variable like the one defined below will exist in the integer cache.

Integer C = 100; // 100 between-128 and 127. 

The internal implementation is:

Integer i = integer.valueof (100);

Now look again at the valueof () method and you will see the following implementation code:

/*** 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 * Caching freq Uently 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) {assertIntegercache.high >= 127; if(I >= integercache.low && i <=Integercache.high)returnIntegercache.cache[i + (-Integercache.low)]; return NewInteger (i);} If the value is-between 128 and 127 of the range, it returns the actual value from the cache. So the integer c= +, d = 100; it actually points to the same object. This is when the variables C and D are compared (==) is the result of true. System.out.println (c= = d);//trueNow you might ask, why does this need to be cached? The logical rationale is that the "smaller" integers in this range are much larger, so using the same underlying object is worthwhile to reduce the potential memory footprint. The following code obtains an integer cache variable through reflection.  Public classIntegerdemo { Public Static voidMain (string[] args)throwsnosuchfieldexception, illegalaccessexception {Class cache= Integer.class. getdeclaredclasses () [0];//1Field Mycache = Cache.getdeclaredfield ("cache");//2Mycache.setaccessible (true);//3Integer[] Newcache = (integer[]) mycache.get (cache);//4     for(inti = 0; i < newcache.length; i++) {System.out.printf ("Index[%d]-->vlaue[%d]\n", I,newcache[i]); }   } }
Reprinted from:
Lin Supplement Link: https://zhuanlan.zhihu.com/p/20703688 Source: The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

[Reprint] In Java why the variable 1000 = 1000 returns false, but 100=100 returns true?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.