Jashan Chahal
Jashan Chahal

Reputation: 291

Concatenation of two string in String constant pool in java

Since concatenation of two strings will make new string object in string constant pool so why following code evaluates to No.

public class Main {
    public static void main(String[] args) {
        String s = "abcd";
        String s1 = "ab";
        String s2 = "cd";
        s1 = s1+s2;
        if(s1==s)
            System.out.println("YES");
        else
            System.out.println("No");
            }
}

Upvotes: 3

Views: 70

Answers (2)

Eklavya
Eklavya

Reputation: 18430

Here s has complied time assign value and s1 is in runtime both are not same instance String pool. Use equals method to check equals in string for this case ex: s1.equals(s).

If both values computed in runtime this will work.

String s1 = "ab";
String s2 = "cd";
String s3;
s1 = s1+s2;
s3 = s1;
if(s1==s3)
    System.out.println("YES");
else
    System.out.println("No");
}

It gives you output YES.

And if both values assigned in compile time then it will work.

String s = "abcd";
String s1 = "abcd";
if(s1==s)
    System.out.println("YES");
else
    System.out.println("No");
}

This code also gives you output YES

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140318

s1+s2 is not a compile-time constant expression because s1 and s2 aren't final (despite them being assigned compile-time constant values).

As such, the value is computed at runtime: the result is not the same instance as the one in the constant pool, despite the value being the same.

Upvotes: 6

Related Questions