Lot of questions has been already asked about the differences between string and string builder and most of the people suggest that string builder is faster than string. I am curious to know if string builder is too good so why string is there? Moreover, can some body give me an example where string will be more usefull than string builder?
If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.
The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters. Unlike Strings, objects of type StringBuffer and String builder can be modified over and over again without leaving behind a lot of new unused objects.
Although the score difference isn't much, we can notice that StringBuilder works faster. Fortunately, in simple cases, we don't need StringBuilder to put one String with another. Sometimes, static concatenation with + can actually replace StringBuilder.
A String is immutable in Java, while a StringBuilder is mutable in Java. An immutable object is an object whose content cannot be changed after it is created. When we try to concatenate two Java strings, a new String object is created in the string pool.
StringBuilder is, as its name suggested, is used to build strings, whereas strings are immutable character-values. Use strings when you want to pass around character data, use StringBuilder when you want to manipulate character data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With