From what I understand, the String concatenation "+" operator in Java is implemented using Stringbuilder, such that something like :
String s = "foo" + "bar"
internally compiles as :
String s = new StringBuilder().append("foo").append("bar").toString();
So I tried something like this :
String foo1 = "foobar";
String foo2 = new String("foobar");
String foo3 = "foo" + "bar";
char[] fooarray = {'f','o','o','b','a','r'};
String foo4 = new String(fooarray);
Next I tested these against each other using == operator. The results were mostly what I expected : foo2 and foo4 did not return "==" for any other String.
However , foo3 == foo1 returns true. What is the reason for this ? The StringBuilder class's toString method internall calls "new String" , so shouldn't foo3 be a unique object, just like foo2 ?
"foo" + "bar"is the same as writing"foobar". It allows you to split a string literal over multiple lines, without performance penalty.final, then even,String s = s1 + s2will happen at compile time ifs1ands2are references to String literals