Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String equality vs equality of location

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?

like image 779
BloodParrot Avatar asked Feb 27 '09 12:02

BloodParrot


People also ask

What is the difference between string equals and == in Java?

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.

Can string be compared with ==?

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.

What does == mean for strings in Java?

== 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 // ...

How do you check if a string equals something?

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.


2 Answers

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.

like image 103
Bill the Lizard Avatar answered Sep 24 '22 15:09

Bill the Lizard


You explicitly call new for s3 and this leaves you with a new instance of the string.

like image 23
sharptooth Avatar answered Sep 21 '22 15:09

sharptooth