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".