Search code examples
javastringstringbuilder

String vs String builder. which is faster? If stringbuilder then why use string


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.


Solution

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