Gagan93
Gagan93

Reputation: 1876

String Pool related concept but confusing

Consider the following code with comments

public class Demo
{
    public static void main(String aa[])
    {
        String hello="Hello",lo="lo",hel="Hel";
        System.out.println(other.hello=="Hel"+lo); // returns false because new strings are created
        System.out.println(other.hello==hel+lo); // returns false, same reason i think. Comment if i am not correct
        System.out.println(other.hello=="Hel"+"lo"); // returns true, how ?
    }
}
class other
{
    static String hello="Hello";
}

The first prints false because new Strings are created before comparison (correct me if I am wrong). Second also prints false due to the same reason I think. But the third statement prints true. How this happens or what is the reason behind this ?

Upvotes: 0

Views: 43

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200148

This expression:

"Hel"+"lo"

is a constant expression, which means that it is evaluated at compile time. Therefore the expression has the exact same treatment as the explicit string literal

"Hello"

which, BTW, is just another example of a constant expression. Quoting JLS §15.28:

Constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.

Upvotes: 3

TheLostMind
TheLostMind

Reputation: 36304

Answering inline.

public static void main(String aa[])
    {
        String hello="Hello",lo="lo",hel="Hel";
        System.out.println(other.hello=="Hel"+lo); // returns false because new string is created
        System.out.println(other.hello==hel+lo); // returns false, same reason. Right
        System.out.println(other.hello=="Hel"+"lo"); // returns true, because "hel" + "lo" will be resolved to "hello" during compile time. So, Since "Hello" has already been added to the String constants pool, the reference to the same will be used here.
    }

Upvotes: 0

Orel Eraki
Orel Eraki

Reputation: 12196

Every string in the program is given a matching key.

If after concatenation you create a string that matches the same string literal that was already present, then they both are equal and pointing to the same value.

Upvotes: 0

Related Questions