Possible Duplicate:
String, StringBuffer, and StringBuilder
What 开发者_Python百科are common methods between String and StringBuffer? And what is the difference between string and string buffer?
The biggest difference is that String
is immutable and StringBuffer
is mutable.
StringBuffer
lets you join strings faster. For example the following code:
String s = "Initial string ";
for (int i = 0; i < 100; i++) {
s = s + i;
}
on every iteration creates a string representing integer i
and than also creates a new string of s
and i
joined together and moves s
reference to this new object. It does not reuse the same s
object by expanding its content.
StringBuffer
lets you append string more efficiently. There is also a newer version of this class called StringBuilder
which is basically StringBuffer
without synchronization.
The first few lines on the StringBuffer
JavaDoc give a pretty good answer:
A thread-safe, mutable sequence of characters. A string buffer is like a
String
, but can be modified.
The most obvious shared methods are those specified by the interface implemented by both String
and StringBuffer
(as well as StringBuilder
): Appendable
. It provides 3 methods for appending other values.
When you need to concatenate many String literal together, then it might be better off for you to use a StringBuffer
object, and as when you are done with the concatenation, turning it into a String
object using the toString()
method.
EDIT: Please ignore the lines below
The below instantiates 6 String objects in the String pool theoretically.
String a = "A" + "B" + "C" + "D" + "E";
精彩评论