Java has separate memory for strings that are created without calling the constructor with new . Each time such a line is created, Java checks to see if this line is in this memory. If so, then Java sets the same link to a new line until one of them changes.
When you create a String with a constructor using new , it behaves like a regular object in Java.
Take a look at this example:
String s1 = "Test"; String s2 = "Test";
When you compare this string with the == operator, it will return true. s1.equals(s2) will also return true.
It looks like if you create String objects with the following constructor:
String s1 = new String("Test"); String s2 = new String("Test");
When you now compare these strings with the == operator, it will return false, because the link to these strings is now different (you created 2 unique String objects). But if you use s1.equals(s2) , it will return true as expected.
source share