String s1 = 'BloodParrot is the man'; String s2 = 'BloodParrot is the man'; String s3 = new String('BloodParrot is the man'); System.out.println(s1.equals(s2)); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1.equals(s3));
// output
true
true
false
true
Why don’t all the strings have the same location in memory if all three have the same contents?
Java only automatically interns String literals. New String objects (created using the
newkeyword) are not interned by default. You can use the String.intern() method to intern an existing String object. Callinginternwill check the existing String pool for a matching object and return it if one exists or add it if there was no match.If you add the line
to your code right after you create
s3, you’ll see the difference in your output.See some more examples and a more detailed explanation.
This of course brings up the very important topic of when to use == and when to use the
equalsmethod in Java. You almost always want to useequalswhen dealing with object references. The == operator compares reference values, which is almost never what you mean to compare. Knowing the difference helps you decide when it’s appropriate to use == orequals.