问题
Why below s3
and s5
String
objects are differ, When s5
try to created in String pool it checks content s3
already have same content so s5
refers s3
object in string pool. But my assumption is wrong, then any one correct me.
String s1="Buggy";
String s2="Bread";
String s3="BuggyBread";
String s4 = "Buggy"+"Bread";
String s5 = s1 + s2
System.out.println(s3==s4); // True
System.out.println(s3==s5); //false
回答1:
String s4 = "Buggy" + "Bread";
The compiler is smart enough to realize this is just the constant
BuggyBread
which is already referenced ins3
. In other words,s4
references the sameString
ass3
that is in the string pool.String s5 = s1 + s2;
Here the compiler faithfully translates to a
StringBuilder
-based concatenation of the contents of the variables, which yields a difference reference thans3
. In other words, this is similar to:StringBuilder sb = new StringBuilder(s1); sb.append(s2); String s5 = sb.toString();
回答2:
Just try this
String s = "Buggy";
s = s.concat("Bread");
System.out.println(s);
来源:https://stackoverflow.com/questions/30275117/why-concatenation-of-two-string-objects-reference-not-equal-to-same-content-stri