Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation of two string in String constant pool in java

Tags:

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");
            }
}
like image 432
Jashan Chahal Avatar asked Dec 17 '25 19:12

Jashan Chahal


1 Answers

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.

like image 86
Andy Turner Avatar answered Dec 20 '25 07:12

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!