Saturday, July 13, 2019

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...