What is the best way to concatenate two Strings in java. likely best performance and less memory usage. Please help me..!
Asked
Active
Viewed 187 times
-4
-
4The best way is not asking this question here and make a minimal research. – Maroun Nov 05 '14 at 08:37
-
Use `StringBuilder`. – Rohan Nov 05 '14 at 08:38
-
I would've suggested `string1 += string2` but I can't guarantee that it has the best performance and least memory usage. – Cupple Kay Nov 05 '14 at 09:27
1 Answers
2
StringBuilder stringBuilder = new StringBuilder(firstString);
stringBuilder.append(secondString);
String string = stringBuilder.toString();
But according to @a_horse_with_no_name the following is even more efficient
StringBuilder sb = new StringBuilder(firstString.length() + secondString.length());
sb.append(firstString);
sb.append(secondString);
String string = sb.toString();

EpicPandaForce
- 79,669
- 27
- 256
- 428
-
2`new StringBuilder(firstString.length() + secondString.length()); sb.append(firstString); sb.append(secondString);` should be more efficient – Nov 05 '14 at 08:38