From what I read in my java book, String and Stringbuffer are exactly the same except that you can change parts of String Buffer, and not String.. So my question(s) is(are) this:
Why would you use String rather than StringBuffer at all, when there are so many advantages to stringbuffer? Why teach about String at all, and not just teach people about Stringbuffer? Or better yet, why didnt they just give the abilitys of stringbuffer to string to begin with?
/======\/-Computrius-\/=======\<br />"Windows 95 is a 32-bit extension to a 16-bit shell for an 8-bit OS made for a 4-bit processor by a 2-bit company that cant stand 1-bit of competition." -- Unknown
Strings are immutable, which means that you can not change their contents. This is very useful for things that represent "primitive" kinds of values, like numbers and strings and such. It allows you do to something like:
Because the string is immutable, I know that no matter how hard you try (or how sloppy you are), there is no way that your method can change myString. It will still be "Hello World" when it gets back from the method. If you used a StringBuffer, then yourMethod could muck around and change the innards of myString. It also lets you do assignments and things without worying about what might happen with the contents of the string, as in:
If strings were not immutable, we wouldn't be so sure about the value of three (or four, either) at the end of this. There are lots of advantages to immutability. But of course as you have seen, it can be inconvenient in some situations. That's why there's StringBuffer - to handle those situations.
Originally posted by Joshua Austin: <snip> So my question(s) is(are) this:
Why would you use String rather than StringBuffer at all, when there are so many advantages to stringbuffer? </snip>
Excellent question Joshua, The answer really lies in that fact that StringBuffers are synchronized. Thus, for minor String manipulations(say, less then 300), you're better off using Strings(which are immutable, and thus inherently threadsafe). However, for major ones, use a StringBuffer. This advice becomes even more true if you're Threading. HTH, M, author The Sun Certified Java Developer Exam with J2SE 1.4
Why would you use String rather than StringBuffer at all, when there are so many advantages to stringbuffer? The answer must be that Strings have some advantages in some situations over StringBuffers. Since Strings are immutable, the JVM (and compiler I think) are able to perform some efficiency tricks with memory allocation and object creation. One such trick is String pooling. The basic idea with String pooling is simple. If a given String has already been created, use it again if the program tries to create a new one that is identical. Since Strings cannot be changed once created, this won't cause any conflicts due to changing object values. Since a StringBuffer may change its value, this wouldn't work so well. Making any sense?