I know this question has been answered many times in many sites many years ago.:P Still I have some doubt so thought of posting this. The basic difference is, String is immutable and each time we do any operation on String it creates a new String Object.
Ex:-
String str = "some";
str = str + " text"
In above case 2 new Strings get created instead of modifying the existing str which can be avoided by using StringBuffer.
Ex:-
StringBuffer str = new StringBuffer();
str.append("try");
str.append("this");
My question here is, to append method we are passing a String again. Do new String objects not get created for "try" and "this" in String pool in above case.
Yes, new String objects get created for "try"
and "this"
. The benefit here is that the StringBuffer stores the string of characters internally as a dynamically resized array.
It's more obviously beneficial if we were to concatenate more than two Strings:
"try" + "this" + "test"
This would potentially create 5 String objects because you need intermediate values. (Technically concatenation of literals is performed at compile time so this is just a conceptual example.) It would also be typical for a compiler to refactor the above snippet in to using StringBuilder
anyway if they were not literals.
StringBuilder
is a newer and non-synchronized version of StringBuffer
. In general, you should prefer StringBuilder
. The difference between these two classes is covered in "StringBuilder and StringBuffer in Java".