Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference id of two String in constant pool

Tags:

java

Visit String Constant Pool Java !

public class StringLiterals {
    public static void main(String[] args) {
        String s1="This is ";
        s1=s1+"my book";
        String s2="This is my book";
        System.out.println(s1==s2);

    }
}

O/P:False

Expecting O/P:True

like image 421
Barnwal Vivek Avatar asked Dec 26 '22 14:12

Barnwal Vivek


1 Answers

Maybe this will help clear things up.

    String s1 = "This is";
    s1 = s1 + " my book"; // Note the space
    String s2 = "This is my book";
    String s3 = "This is my book";
    System.out.println(s1==s2); // False
    System.out.println(s2==s3); // True

"Strings are only put in the pool when they are interned explicitly or by the class's use of a literal." Hence, you cannot concatenate strings with the + operator and expect it to be put into the string constant pool.

like image 174
Kent Shikama Avatar answered Jan 08 '23 13:01

Kent Shikama