Monday 6 January 2020

Strings in Java : equals vs ==

Answer


Answer






Possible Duplicate:
How do I compare strings in Java?






  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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...