Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String addition in Java showing unexpected behavior [duplicate]

Tags:

java

string

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?

like image 766
Suhail Avatar asked Feb 15 '23 11:02

Suhail


1 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.

like image 55
arshajii Avatar answered Feb 17 '23 01:02

arshajii