Sagar Pudi
Sagar Pudi

Reputation: 4824

String or StringBuilder which takes less time to initialize? And which one is preferable to use?

My program want to store Strings and no need to perform any operations on those except storing information as it is.

Then which of the following way is preferrable?

String s = new String("sagar");

or

StringBuilder sb = new StringBuilder("sagar");

Upvotes: 1

Views: 178

Answers (5)

Sivaram
Sivaram

Reputation: 21

it is based on the using.

Actually at the time of concatenation String builder is effective than Strings.

In String Concatenation you can use String builder.

String builders are not thread safe so if you working on single thread it is effective but its not for multi-threading and Strings are immutable

Upvotes: 1

Manoj
Manoj

Reputation: 539

You should use String s = "sagar"; because it enables string literal pooling.

What is string literal pooling? - Like any other object creation,String creation/allocation is a memory and time consuming operation. Hence whenever a string is created it will refer to the string pool for the similar object, If such a string exists then it will refer the same.

This feature is possible as strings are immutable in java. Eventually string literal pooling will enhance the performance.

String Builder are intended for manipulations with Strings like concat().

Upvotes: 1

Gabriel Negut
Gabriel Negut

Reputation: 13960

For storage - String

For manipulation - StringBuilder

Upvotes: 0

Vihar
Vihar

Reputation: 3831

For your question "which of the following way is preferrable?"

it really depends on your usage.

If you need to really perform manipulations on your string then StringBuilder is more useful then a normal String.

Moreover StringBuffer is also thread safe so it can be used effectively in a multithreaded environment.

Strings are immutable in nature.

Hope this helps!

Good luck.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

A String is a reference to an instance in the String intern pool. Since you aren't performing any string concatenation or manipulation here, I would use

 String s = "sagar";

I would not use

 String s = new String("sagar");

Because that ignores the intern pool. As for the StringBuilder I would prefer that when manipulating the value because (in contrast to String) it is mutable.

Upvotes: 3

Related Questions