Weird Java question: Why does 128 == 128 return False, but 127 == 127 returns True?

Weird Java question: Why does 128 == 128 return False, but 127 == 127 returns True?

This is the topic we are going to discuss today because I think it is very interesting.

If you run the following code:

  1. Class A
  2. {
  3. public   static void main(String[] args)
  4. {
  5. Integer a = 128, b = 128;
  6. System. out .println(a == b);
  7. Integer c = 127, d = 127;
  8. System. out .println(c == d);
  9. }
  10. }

You will get the following result:

  1. false  
  2. true  

We know that if two references point to the same object, then == is true; conversely, if the two references do not point to the same object, then == is not true, even if the contents of the two references are the same. Therefore, the result will be false.

This is where it gets really interesting. If you look inside the Integer.java class, you’ll find an inner private class called IntegerCache.java that provides a cache for all integer objects between -128 and 127.

This thing provides an internal cache for small integers, and when declared like this:

  1. Integer c = 127

This is what it looks like inside:

  1. Integer var3 = Integer .valueOf(127);

In fact, after I decompile the A.class file, the code is as follows:

If we look at the valueOf() class function, we can see:

  1. public   static   Integer valueOf( int i) {
  2. if (i >= IntegerCache.low && i <= IntegerCache.high)
  3. return IntegerCache.cache[i + (-IntegerCache.low)];
  4. return new Integer (i);
  5. }

If the value is between -128 and 127, it returns an instance of that cache.

therefore...

  1. Integer c = 127, d = 127;

Both refer to the same object.

That's why the following code evaluates to true:

  1. System.out.println (c == d) ;

Now you might ask, why would there be a cache for all integers between -128 and 127?

This is because the frequency of use of small integers in this range is much greater than that of other integers in daily life, and the fact that the same underlying object is used multiple times can be effectively optimized for memory through this setting. You can use this feature arbitrarily using the reflection API.

Run the following code and you will see the magic.

  1. public   static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
  2.  
  3. Class cache = Integer .class.getDeclaredClasses()[0];
  4. Field myCache = cache.getDeclaredField( "cache" );
  5. myCache.setAccessible( true );
  6.  
  7. Integer [] newCache = ( Integer []) myCache.get(cache);
  8. newCache[132] = newCache[133];
  9.  
  10. int a = 2;
  11. int b = a + a;
  12. System. out .printf( "%d + %d = %d" , a, a, b); //
  13. }

The print result is:

  1. 2 + 2 = 5

Let's look at the disassembled code again:

Is this the same problem as above?

But why is the result 2 + 2 = 5?

Let's continue to look at the Integer source code to gain a deeper understanding of the Integer cache mechanism. Here is a screenshot:

According to the source code, we can find that the method of modifying the upper limit of the Integer cache has some minor flaws. Let's take a look at what the API suggests to us:

  1. the size   of the cache may be controlled by the {@code -XX:AutoBoxCacheMax=< size >} option .

It turns out that we only need to set -XX:AutoBoxCacheMax=133 at runtime.

<<:  Android performance optimization memory leak

>>:  How to use fastboot to flash the original image to Android

Recommend

Stories can't save Zhihu

Zhihu, a question-and-answer community launched i...

Will it be uncomfortable if a girl reacts? How do girls react when they want it?

Belly wonder if now is a good time to ask for a h...

[A magic tool for watching movies anytime, anywhere] PaPa Pocket Cinema Review

Product highlights: small and portable, built-in ...

The dream of a minimalist smartphone is beautiful, but the reality is bleak

On July 1, Wired published an article saying that...

I would like to call this Android automation APP a magic tool!

[[385362]] Friends who have used Android phones s...

How much does it cost to customize a jewelry mini program in Hezhou?

The launch of mini programs has brought convenien...

Kai-Fu Lee recommends: Ten design thinking skills you must know

Course Location: R-63 In the Zhihu course "L...

Difference between FragmentPagerAdapter and FragmentStatePagerAdapter

FragmentPagerAdapter and FragmentStatePagerAdapte...

Tesla asks suppliers to refund money, trying hard to save cash flow

Tesla asked some suppliers to return part of the ...

Three reasons why domestic mobile phone systems are tepid

[[156212]] This year's Double Eleven, while s...