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?
In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method.
After using the intern() method on a string reference obtained using new, we can use the == operator to compare it with a string reference from the string pool.
== is for testing whether two strings are the same Object . // These two have the same value new String("test").equals("test") ==> true // ... but they are not the same object new String("test") == "test" ==> false // ...
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
Java only automatically interns String literals. New String objects (created using the new
keyword) are not interned by default. You can use the String.intern() method to intern an existing String object. Calling intern
will 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
s3 = s3.intern();
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 equals
method in Java. You almost always want to use equals
when 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 == or equals
.
You explicitly call new for s3 and this leaves you with a new instance of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With