Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How string literals are stored in String Constant Pool ? Why isn't "Hello " + world in the string constant pool?

Java Code


class Other {
    static String hello = "Hello World";
}

public class Main {

    public static void main(String[] args) {
       
        String hello = "Hello World", world = "World";

        System.out.println(Other.hello == hello);                   // Line1
        System.out.println(hello == ("Hello " + "World"));          // Line2
        System.out.println(hello == ("Hello " + world));            // Line3
        System.out.println(hello == ("Hello " + world).intern());   // Line4

        System.out.println(Integer.toHexString(hello.hashCode()));
        System.out.println(Integer.toHexString(("Hello " + "World").hashCode()));
        System.out.println(Integer.toHexString(("Hello " + world).hashCode()));
        System.out.println(Integer.toHexString(("Hello " + world).intern().hashCode()));
    }
     
}

I expect Line3 to return true but it is returning false. Kindly help me.

Output
true true false true
42628b2 42628b2 42628b2 42628b2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Only string literals are automatically stored in the String Constant Pool.

The following is a string literal:

"Hello " + "world"

The following is not a string literal:

String world = "world";
"Hello " + world

This is specifically stated in the Java Language Specification:

A long string literal can always be broken up into shorter pieces and
written as a (possibly parenthesized) expression using the string
concatenation operator +

Why isn’t "Hello " + world in the string constant pool? Simply because the JLS says so. That’s what the language designers decided.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading