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

前端 未结 5 1272
余生分开走
余生分开走 2020-12-06 01:27

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 o

5条回答
  •  生来不讨喜
    2020-12-06 02:18

    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.

提交回复
热议问题