"String" is an object in Java, so "==" compares the links as indicated. However type code
String str1 = "dog"; String str2 = "dog"; if(str1==str2) System.out.println("Equal!");
actually prints "Equal!", which may confuse you. The reason is that the JVM optimizes your code a bit when directly assigning literals to String
objects, so str1 and str2 actually refer to the same object that is stored in the internal pool inside the JVM. Code, on the other hand
String str1 = new String("dog"); String str2 = new String("dog"); if(str1==str2) System.out.println("Equal!");
nothing will print because you explicitly stated that you want two new objects.
If you want to avoid complications and unexpected errors, simply never use "==" with strings.
source share