String addition in Java showing unexpected behavior

Viewed 125

I have this code in Java :

    String s0="ab";
    String s1="bc";
    String s2="abbc";
    String s3="ab"+"bc";
    String s=s0+s1;

When i try to compare s & s2 using if(s==s2), it returns false,
But on comparing s2 & s3 using, if (s2==s3) returns true.

Why is the output not same in both the cases?

2 Answers

String s3 is being assigned to a compile-time constant which is exactly equivalent to "abbc". Hence, s2==s3 compares two identical string literals, which results in true since these literals are interned.

s0+s1 is not a compile time constant, so a new string object is produced. Therefore, s==s2 returns false.


In terms of byte code,

String s3="ab"+"bc";

becomes

LDC "abbc"
ASTORE 1

Notice that "abbc" is used directly.


Lastly, if you declare s0 and s1 to be final, then s0+s1 would be a constant expression and s==s2 would be true.

The == operator compares the pointers of the objects, not the objects themselves. To compare string values you should use either equals(..) or equalsIgnoreCase(..), whichever is appropriate.

The strings s2 and s3 are probably comparing as equal because they are being interned behind the scenes. Interning is taking commonly used strings, holding them in (I think) PermGen and just using a single reference for that string. This is useful when you have a lot of strings with the same value and works because strings are non-mutable. Whenever you add something to a string a new string is created.

Related