According to SCJP Study Guide by KathySierra:
The java.lang.StringBuffer and java.lang.StringBuilder classes should be used when you have to make modifications to strings of characters. As we discussed, String objects are immutable, so if you choose to do a lot of manipulations with String objects, you will end up with a lot of abandoned String objects in the String pool
To clear out this, I have gone through the code of String class and StringBuilder source here.
The simplfied code of String looks like this:
public final class String(){
private final char [] value; //Final helps in immutability, I guess.
public String (String original){
value = original.value;
}
}
And StringBuilder's simplified version look like this:
public final class StringBuilder{
char [] value;
public StringBuilder(String str) {
value = new Char[(str.length() + 16)]; // 16 here is implementation dependent.
append(str);
}
public StringBuilder append(String str){
//Add 'str' characters in value array if its size allows,
else
// Create new array of size newCapacity and copy contents of 'value' in that.
//value = Arrays.copyOf(value, newCapacity);// here old array object is lost.
return this;
}
}
So let's say we have a case as under:
Using String class:
String s1 = "abc"; // Creates one object on String pool.
s1 = s1+"def"; // Creates two objects - "def " on String pool
// and "abcdef" on the heap.
If I use StringBuilder, the code becomes:
StringBuilder s1 = StringBuilder("abc");
// Creates one String object "abc " on String pool.
// And one StringBuilder object "abc" on the heap.
s1.append("def");
// Creates one string object "def" on String pool.
// And changes the char [] inside StringBuilder to hold "def" also.
In StringBuilder s2 = s1.append("def"); there are equal chances that the char array holding the string will be replaced by a new char array. The old array is reference less now and will be garbage collected.
My Query is:
Using simple String concatenation and StringBuilder append() method, the number of String objects that go on to the String pool is same.
And according to the code listed above, StringBuilder does make use of bigger char arrays in the first place while the String object contains a char array of the same length as the string it is holding.
- How is the usage of
StringBuildermore efficient than normalStringclass for string manipulations? - And is the statement given in
SCJP Guidewrong?