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 and s2 using if(s==s2), it returns false,But when comparing s2 and s3 using if (s2==s3)returns true.Why is the conclusion not the same in both cases?
if(s==s2)
false
if (s2==s3)
true
The string s3is assigned a compile-time constant that is exactly equivalent "abbc". Therefore, it s2==s3compares two identical string literals, which results in truesince these literals are interned.
s3
"abbc"
s2==s3
s0+s1 , . s==s2 false.
s0+s1
s==s2
String s3="ab"+"bc";
LDC "abbc" ASTORE 1
, "abbc" .
, s0 s1 final, s0+s1 , s==s2 .
s0
s1
final
== , . , equals(..), equalsIgnoreCase(..), , .
==
equals(..)
equalsIgnoreCase(..)
s2 s3, , , . Interning , ( ) PermGen . , , . , - , .
s2