i am confused between string and string builder which is faster, i know string builder is faster than string in concatenation operations. But what if i don't want to use concatenation operations. If stringbuilder is faster why we mostly use string.
-
For concat 2 strings, once, there is no real need of use StringBuilder, which is more when you need complex chaining or loop chaining – azro Apr 13 '20 at 07:54
-
2`StringBuilder` is faster at **building strings**, i.e. concatenating strings. If you don't need concatenation, then use a `String`, since a `StringBuilder` would be overkill, and slower. – Andreas Apr 13 '20 at 07:54
-
1Does this answer your question? [StringBuilder vs String concatenation in toString() in Java](https://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java) – Modus Tollens Apr 13 '20 at 08:02
-
Another possible dupe: https://stackoverflow.com/q/5234147/1288408 – Modus Tollens Apr 13 '20 at 08:03
1 Answers
The advantage of String
is that it is immutable: once constructed, the contents of a string instance cannot change anymore. This means that you pass strings by reference without making copies all the time.
For example, suppose you would pass a StringBuilder
to a class. Then you could change the contents of that StringBuilder
afterwards, and confuse the class. So the class would need to make a copy to make sure that the content doesn't change without it knowing about it. With a String
this is not necessary, because a String
is immutable.
Now, when you're in the process of building a string, this immutability is actually a problem, because a new String
instance must be created for every concatenation. That's why the StringBuilder
class exists: it is an auxiliary class which is intended to build strings (hence the name).
In practice, it's often not necessary to use a StringBuilder
explicitly. The Java compiler will automatically use a StringBuilder
for you when you write things like String result = "some constant" + a + b;
. Only with complex building logic (using if
and for
blocks, for example) you need to do that yourself.

- 12,677
- 8
- 34
- 50