According to the KathySierra SCJP Tutorial:
The java.lang.StringBuffer and java.lang.StringBuilder classes should when you need to make changes to character strings. As we discussed, String objects are immutable, so if you decide to do this a lot of manipulation of String objects, you will get many abandoned String objects in the string pool
To fix this, I looked at the String class code and the StringBuilder source here .
A simple line code is as follows:
public final class String(){
private final char [] value;
public String (String original){
value = original.value;
}
}
And the StringBuildersimplified version is as follows:
public final class StringBuilder{
char [] value;
public StringBuilder(String str) {
value = new Char[(str.length() + 16)];
append(str);
}
public StringBuilder append(String str){
else
return this;
}
}
So, let's say we have a case like:
Using the 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 will look like this:
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.
StringBuilder s2 = s1.append("def"); , char, , char. .
:
String StringBuilder append(), String, , .
StringBuilder char, String char , , .
StringBuilder ,
String ?- ,
SCJP Guide, ?