简体   繁体   中英

Why == is different for Integer and String?

main(){

Integer i1 = 500;

Integer i2 = 500;

System.out.println(i1 == i2);  // O/P is "**false**"

String s1 = "Hello";

String s2 = "Hello";

System.out.println(s1 == s2);  // O/P is "**true**"

} // End of main.

I am not able to figure out why the output is different. As far as I know s1, s2 will point to the same object on the heap. So their reference address are same. Similarly I think Integer is also the same. But it is not. Why is it different?

It has been already answered here: java: Integer equals vs. ==

Taken from this post: The JVM is caching Integer values. == only works for numbers between -128 and 127. So it doesn't work with 500 in your example.

Use string1.equals(string2); //Used for String values

Instead of using string1 == string2; //Used for integer values

Hope this helps.

The answer in this question should help explain it: How to properly compare two Integers in Java?

Pretty much you answered your own question. The "==" is not only comparing the reference points in strings, but it seems to do the same thing with integers.

The way you specified "Hello" does no heap allocation. Instead, "Hello" as a static compile-time constant will be outsourced to the specific section of the executable and referenced. Thus, both references will point to the same address.

So there is Java String Pool and here s1 and s2 actually the same links. In case of Integers, there is also pool but it exists only for Integers -127 till 128

So if you have

Integer i1 = 100;

Integer i2 = 100;

Then i1==i2 will be true

"==" always compare the memory location or object references of the values. equals method always compare the values.but equals also indirectly uses the "==" operator to compare the values. Integer uses Integer cache to store the values from -128 to +127.If == operator is used to check for any values between -128 to 127 then it returns true. for other than these values it returns false .

In string, if string is initialized like this

    String s1="abc"
    String s2="abc"

String s1 and s2 are pointing the same location in memory or String pool.

if string is initialized like this

    String s1=new String("abc"); 
    String s2=new String("abc");

String s1 is pointing the new location in which it contains String "abc" String s2 is pointing the new location in which it contains String "abc" but s1's location is different from s2's location.In that situation equals method is useful for string comparison.

Refer the link for some additional info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM