Adding a string in Java shows unexpected behavior

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?

+4
source share
2 answers

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.

s0+s1 , . s==s2 false.


String s3="ab"+"bc";

LDC "abbc"
ASTORE 1

, "abbc" .


, s0 s1 final, s0+s1 , s==s2 .

+7

== , . , equals(..), equalsIgnoreCase(..), , .

s2 s3, , , . Interning , ( ) PermGen . , , . , - , .

+1

All Articles