First of all, I searched about this in both S.O. and Google. If you say this is a duplicate of something somewhere, that something is being really hard to reach.
Well... we know Strings are Objects and must be compared by using equals, right?
Then, please, explain that:
String s1 = new String("string");
String s2 = new String("string");
String s3 = "string";
System.out.println(s1.equals(s2)); // true
System.out.println(s1 == s2); // false
System.out.println(s1 == "string"); // false
System.out.println(s2 == "string"); // false
System.out.println(s3 == "string"); // true
Regarding the == "string"
outputs, why does only the last one prints "true"?
When they're created, they aren't all Strings? Is now my third String the ugly duckling? ...Worse: if I'm working with a foreign String... it may not be the String that I think it is?! (Notice that s3 has String
before it, not some primitive.)
...I'm pretty sure s3 has an object inside it.
In other words, what's the difference between declaring a String like this:
String s1 = new String("string");
and another like this:
String s3 = "string";
?