Raj
Raj

Reputation: 213

Reference equality for String literals

I have the following code snippet.I am getting the output as false for the reference equality of the strings s1 and s2.

Should not this be true? Strings are immutable in Java and when I create s2 with the same content as s1 (I hate Winters), the reference s2 will simply point to the already existing String object which is being pointed by s1.

public static void main(String[] args) {

    String s1="I hate"; 
    s1=s1+" Winters"; 

    String s2="I hate Winters";

    System.out.println(s1==s2);
}

Upvotes: 1

Views: 49

Answers (1)

Maroun
Maroun

Reputation: 95978

In your program, calculations are made at runtime, the compiler doesn't know that s1 and s2 will be equal strings, so it won't be part of the constant pool. If you do:

String s1 = "I hate Winters"; 
String s2 = "I hate" + " Winters"; 

Concatenation will occur at compile time, and they'll point to the same literal in the pool.

Upvotes: 3

Related Questions