This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
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.
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 L�ubli, SCJP 1.4, CLP 5.0, SCWCD 1.4 (preparing)
Joined: Dec 08, 2004
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.