| Author |
Difference between String and StringBuffer
|
Saurabh Saha
Ranch Hand
Joined: Dec 08, 2004
Posts: 52
|
|
Hi All, Can anyone guide me, what is exact difference between String and StringBuffer. I know that String is immutable and StringBuffer is mutable. But i couldn't understand where we use String and StringBuffer. Please try to explain me in detail if possible. Thanks & Regards, Vivek Mishra
|
 |
Dave Cryder
Greenhorn
Joined: Aug 11, 2004
Posts: 9
|
|
If you are planning on building a string value one piece at a time by appending new values to it, StringBuffer is a better option than String. StringBuffer's append() method actually appends the new part to the existing value. You can "append" to a String, but actually what you are doing is throwing the old value away in favor of the new one. Garbage collection will tidy this up for you in the long run, but with StringBuffer you are not relying on that. At least that's the way it was explained to me.
|
 |
Marcus Laubli
Ranch Hand
Joined: Dec 24, 2004
Posts: 116
|
|
If you're doing lots of String I/O, moving values, etc. StringBuffer is more efficient. Think of the situation where you have to compare or process 100,000 records of data. The object StringBuffer would immediately either go out of scope, or be reassigned a new variable reference. In either case, you're allowing for "cleaner" garbage collection. The way I understand it, especially if you instantiate string outside of your loop, it could take the garbage collector longer to get to the String objects. Hope this helps! Marcus
|
Marcus L�ubli, SCJP 1.4, CLP 5.0, SCWCD 1.4 (preparing)
|
 |
Saurabh Saha
Ranch Hand
Joined: Dec 08, 2004
Posts: 52
|
|
Thanks Dave and Marcus for giving reply, Sorry I couldn't understand much. What I got is, when we need to do lots of String I/O we use StringBuffer otherwise use String. But what is difference between both still not much clear. Please explane me by simple program examples. Thanks & Regards, Vivek Mishra
|
 |
Lionel Badiou
Ranch Hand
Joined: Jan 06, 2005
Posts: 140
|
|
Hi Mishra, The main difference is : * String CAN'T be modified * StringBuffer CAN be modified You may look at the reasons here why two string classes Best regards,
|
Lionel Badiou
CodeFutures Software
|
 |
kunal sinha
Greenhorn
Joined: Jan 21, 2005
Posts: 1
|
|
Hi Vivek got to the following link ..this may serve all ure queries about String and StringBuffer.. http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm Kunal
|
 |
Saurabh Saha
Ranch Hand
Joined: Dec 08, 2004
Posts: 52
|
|
Hi Kunal, Thanks for a good link. This link really solve my all queries about String and StringBuffer. Regards, Vivek Mishra
|
 |
 |
|
|
subject: Difference between String and StringBuffer
|
|
|