Integer object caching

Vidhi Agarwal :

I read that "So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned."

This is the reason why :-

Integer a=100;
Integer b=100;
if(a==b) // return true as both the objects are equal

But why not in this below case? These two values are also in the range of 127 and -128 so according to the statement above this two will also return the same objects.

But the output here i am getting as "Not"

public static void main(String[] args) {

    Integer a = 10;
    Integer b = 12;
    if(a == b)
        System.out.println("same");
    else
        System.out.println("Not");
}

Can someone explain?

Jordan :

You're misunderstanding what "the same object will be returned" means.

So, comparison with == is actually comparing memory locations, and returns true only when the two variables hold the same object (i.e. stored at the same memory location).

Values between -128 to 127 are stored in the integer constant pool, which means that every 10 is the same 10 (i.e. the same memory location), every 12 is the same 12, etc. But it's not the case that all 10s are also 12s, which is what your question is unintentionally assuming.

Anyway, once you get outside of that range, each primitive int is a new object and is assigned to a new memory location outside of the constant pool.

You can test that with the following code:

public static void main(String[] args) {

    Integer a = 1000;
    Integer b = 1000;
    if(a == b)
        System.out.println("same");
    else
        System.out.println("Not");
}

That will print "Not", because a and b are two different objects stored in different memory locations.

And this is why you should compare things with .equals()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308463&siteId=1