Why is 1000 = 1000 in Java false and 100 = 100 true?
This is an interesting topic.
If you run the following code
- Integer a = 1000, b = 1000;
- System.out.println(a == b);//1
- Integer c = 100, d = 100;
- System.out.println(c == d);//2
You will get
False
True
Basic knowledge: we know that if two references point to the same object, they are equal with =. If two references point to different objects, = indicates that they are not equal, even if their content is the same.
Therefore, the following statement should also befalse
.
This is where it is interesting. If you want to seeInteger.java
Class, you will find an internal private class,IntegerCache.java
It caches all integer objects from-128 to 127.
So it becomes, all the small integers are cached internally, and then when we declare something like --
- Integer c = 100;
In fact, what it does internally is
- Integer i = Integer.valueOf(100);
Now, if we look at the valueOf () method, we can see
- public static Integer valueOf(int i) {
- if (i >= IntegerCache.low && i
- return IntegerCache.cache[i + (-IntegerCache.low)];
- return new Integer(i);
- }
If the value range is-128 to 127, it returns the instance from the cache.
So...
- Integer c = 100, d = 100;
Point to the same object.
That's why we write
- System.out.println(c == d);
We can get true.
Now you may ask why cache is required here?
The logical reason is that the usage of small integers in this range is higher than that of large integers. Therefore, using the same underlying object is valuable and can reduce potential memory usage.
However, you may misuse this function through the reflection API.
Run the following code and enjoy its charm.
- public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
-
- Class cache = Integer.class.getDeclaredClasses()[0]; //1
- Field myCache = cache.getDeclaredField("cache"); //2
- myCache.setAccessible(true);//3
-
- Integer[] newCache = (Integer[]) myCache.get(cache); //4
- newCache[132] = newCache[133]; //5
-
- int a = 2;
- int b = a + a;
- System.out.printf("%d + %d = %d", a, a, b); //
- }
Http://www.codeceo.com/article/why-java-1000-100.html.
Why 1000 = 1000 Returns False, but 100 = 100 Returns True in Java?