It was an interview question. I was asked to implement the StringBuffer
append function. I saw the code after the interview. But I cannot understand how the operati
This doesn't compile.
String S= "orange";
S.append("apple");
if you do
final String S= "orange";
final S2 = S + "apple";
This doesn't create any objects as it is optimised at compile time to two String literals.
StringBuilder s = new StringBuilder("Orange");
s.append("apple");
This creates two objects StringBuilder
and the char[]
it wraps. If you use
String s2 = s.toString();
This creates two more objects.
If you do
String S= "orange";
S2 = S + "apple";
This is the same as
String S2 = new StringBuilder("orange").append("apple").toString();
which creates 2 + 2 = 4 objects.