Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)
It is supposed to be generally preferable to use a StringBuilder for string concatenation in Java. Is this always the case?

What I mean is this: Is the overhead of creating a StringBuilder object, calling the append() method and finally toString() already smaller then concatenating existing strings with the + operator for two strings, or is it only advisable for more (than two) strings?

If there is such a threshold, what does it depend on (perhaps the string length, but in which way)?

And finally, would you trade the readability and conciseness of the + concatenation for the performance of the StringBuilder in smaller cases like two, three or four strings?

1 Answer

0 votes
by (46k points)

If you apply String concatenation in a loop, anything like this,

String s = "";

for (int i = 0; i < 100; i++) {

    s += ", " + i;

}

then you should apply a StringBuilder (not StringBuffer) alternatively of a String because it is much quicker and occupies less memory.

If you possess a single comment,

String s = "1, " + "2, " + "3, " + "4, " ...;

then you can apply Strings because the compiler will accept StringBuilder automatically.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...