If == compares references in Java, why does it evaluate to true with these Strings?

java, reference, string

Solution

The program will print `Equal`. (At least using the Sun Hotspot and suns Javac.) Here it is demonstrated on http://ideone.com/8UrRrk

This is due to the fact that string-literal constants are stored in a string pool and string references may be reused.

Further reading:

- What is String literal pool?

- String interning

This however:

public class Salmon {
    public static void main(String[] args) {

        String str1 = "Str1";
        String str2 = new String("Str1");

        if (str1 == str2) {
            System.out.println("Equal");
        } else {
            System.out.println("Not equal");
        }
    }
}

Will print `Not equal` since `new` is guaranteed to introduce a fresh reference.

So, rule of thumb: Always compare strings using the `equals` method.

Problem

As it is stated the == operator compares object references to check if they are referring to the same object on a heap. If so why am I getting the "Equal" for this piece of code? ``` public class Salmon { public static void main(String[] args) { String str1 = "Str1"; String str2 = "Str1"; if (str1 == str2) { System.out.println("Equal"); } else { System.out.println("Not equal"); } } } ```

Original source