• Post Reply Bookmark Topic Watch Topic
  • New Topic

String and StringBuffer  RSS feed

 
Nidhi Singhal
Ranch Hand
Posts: 89
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

As we all know that String class creates immutable strings and if we modify a string then a new string object is created that contains the modifications

But creating new objects everytime uses more memory.
I want to know that then why do we always use String class and not StringBuffer?

thanx..
Nidhi
 
Bajji Pat
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nidhi,

In Strings we have a constant pool so it is optimized internally. So we use String in cases we know that it is not going to be modified frequently, else we go for StringBuffer.

Regards
Balaji Pattabhiraman
 
Reghu Ram Thanumalayan
Ranch Hand
Posts: 193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nidhi,

To elaborate on Balaji's reply, String literals are always returned from the String pool. So you can use string literals safely as many times as you want since they the same literal will be pointing to the single string object in the string pool even when used multiple times.

But if you create a string using new, then the object is created on the heap. And it is not wise to use String when u know that your string will change over time.

For ex, instead of saying,

String name = new String("My Name");
String appendedname = name + new String("Your name");

You can write,

StringBuffer name = new StringBuffer();
name.append("My Name").append("Your Name");

or

String name = "My name" + " Your Name"; // This is equavalent to the above code.

In the first case, two strings are created in the string pool ("My name", "Your name") if they are not already there and two string objects on the heap ("My name", "My name Your name")

In the second case, two on the string pool and one stringbuffer object on the heap.

And for that matter string concatenation using + internally uses StringBuffer only. So it depends on the usage. Hope this helps.
[ April 15, 2005: Message edited by: Reghu Ram T ]
 
Nidhi Singhal
Ranch Hand
Posts: 89
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx alot for the help!!

Regards,
Nidhi
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!