+ 3

String or StringBuffer ?

I recently came up with a statement saying "Use StringBuffer instead of String for optimization of program". And I found that under the hood String creates the temporary StringBuffer object for concatenation of String, but then I tried using concat() method of String and realized that no StringBuffer object was created in the intermediate step. So now which one is more preferred concat() method of String or simply using StringBuffer ?

11th May 2017, 8:42 PM
Preet Patel
Preet Patel - avatar
4 Answers
+ 3
If you concatenate a few String its ok to use String. If you want concatenate a lot of String you should use StringBuilder if you need thread safe then use StringBuffer.
11th May 2017, 9:09 PM
Szabó Gábor
Szabó Gábor - avatar
+ 11
expanding the explanation: String is an immutable object, meaning it CANNOT be change after it been created and each time you add to it: String st = "hello"; st += " world"; you are actually creating a new string in the memory and re-bind the st String.
11th May 2017, 9:33 PM
Burey - avatar
+ 6
StringBuilder is also possible
11th May 2017, 9:04 PM
NimWing Yuan
NimWing Yuan - avatar
+ 4
I made a program what compare the concatenations performance: https://code.sololearn.com/c369kc5K4RQ2/#java
12th May 2017, 1:44 PM
Szabó Gábor
Szabó Gábor - avatar