What is the difference b/w String and Stringbuffer,if u say String is immutable,i can do modification in the string itself.I refered many books,in all i didn't get a clear answer,in some it is given that if u try to append a string using concatination it will use more resources ,i dont understand this .PLZ Help
Hi, Welcome to JavaRanch! Strings are indeed immutable. There are no methods that allow you to change the value of a String object. All the methods like toLowerCase() and concat() that might appear to change the string they're called on, do not actually change it; they create a new String instead. So for instance, the concat() method returns a new string equal to the original string with the argument added on. StringBuffer is really a specialized, extensible array of characters. The main purpose of StringBuffer is to allow you to concatenate many small pieces together to make a large string efficiently. If you write
Then each call to concat creates a new String object. If on the other hand, you write
Then only the last call creates a String object. If you're assembling a lot of pieces together, this can be a lot more efficient that using concat() directly. Note that if you write
The Java compiler will actually emit code using a StringBuffer, much like my second example -- so using the "+" operator isn't as bad as many people will lead you to believe. On the other hand, if you wrote this last example using a separate line of code for each "+" operation, the emitted code would look more like the first example using concat(). Finally, note that despite what many people will tell you, none of this really matters except in an inner loop, or other code that must be highly optimized. In general, don't worry about writing the most efficient code; write the clearest, easiest to understand code. If something turns out to be slow, you can always go back and optimize it later.