Sunday 24 July 2016

Strings in Java : equals vs ==










  String s1 = "andrei";
String s2 = "andrei";


String s3 = s2.toString();

System.out.println((s1==s2) + " " + (s2==s3));


Giving the following code why is the second comparison s2 == s3 true ?
What is actually s2.toString() returning ? Where is actually located (s2.toString()) ?


Answer



First of all String.toString is a no-op:




/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}



Second of all, String constants are interned so s1 and s2 are behind the scenes changed to be the same String instance.


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