Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are strings more useful than a StringBuilder?

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?

like image 735
DJay Avatar asked Jun 18 '10 12:06

DJay


People also ask

When should I use string instead of StringBuilder?

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.

Where do we use string StringBuffer and StringBuilder?

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.

Is StringBuilder more efficient than string?

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.

What is difference between string and 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.


1 Answers

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.

like image 157
Janick Bernet Avatar answered Oct 24 '22 13:10

Janick Bernet