| Author |
String and StringBuffer
|
Nidhi Singhal
Ranch Hand
Joined: Sep 19, 2004
Posts: 89
|
|
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
Joined: Apr 05, 2005
Posts: 50
|
|
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
Joined: Oct 21, 2003
Posts: 193
|
|
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 ]
|
Cheers,<br />Reghu Ram T<br /> <br />SCJP 1.4 - 98 %, SCBCD 1.3 - 94 %, SCMAD 1.0 - 92 %
|
 |
Nidhi Singhal
Ranch Hand
Joined: Sep 19, 2004
Posts: 89
|
|
thanx alot for the help!! Regards, Nidhi
|
 |
 |
|
|
subject: String and StringBuffer
|
|
|