Saturday, 24 September 2016

java - 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?


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...