Java has a separate memory for Strings that are created without calling the constructor with new
. Every time such a String is created Java checks if that String is already in this memory. If it is, then Java sets the same reference to the new String until one of them changes.
When you create a String with the constructor using new
then it behaves as a normal 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 different if you create String objects with the constructor like this:
String s1 = new String("Test");
String s2 = new String("Test");
When you now compare this Strings with the ==
operator it will return false, because the reference of this strings is now different (you created 2 unique String objects).
But if you use s1.equals(s2)
it will return true as expected.