+ 2
What?
Whyyyyy? What's the logic of this? https://code.sololearn.com/cgdsDC8guqfy/?ref=app
1 Resposta
+ 2
hi I am new here its my first post I wish this can solve your problem with this program 😅😅
we know that , if two references point to the same object, they are equal in terms of ==. If two references point to different objects, they are not equal in terms of == even though they have the same contents.
So, here last statement should be false as well.
This actually where it gets interesting, if you look into the Integer.java class , you will find that there is a inner private class, IntegerCache.java that caches all Integer objects between -128 and 127.
So thing is, all small integers are cached internally and when we declare something like –
Integer c = 100;
What it does internally is:
Integer i = Integer.valueOf(100);
Now if we look into the valueOf() method , we will 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 in the range -128 to 127, it returns the instance from the cache.
So
Integer c = 100, d = 100;
basically point to the same object.
Thats why we do –
System.out.println(c == d);
We get true.