 |
StringBuilder was added in Java 5 as an unsynchronized equivalent to StringBuffer, and is recommended in preference to StringBuffer when thread-safety is not an issue. It allows the convenient, incremental construction of String instances through the append and insert methods, which are overloaded to accept a wide range of data types. Essentially, each of these methods converts its argument to a string and then places that string's characters into the string builder. Characters are added at the end by append or at a designated location by insert. Each instance of StringBuilder manages its own internal buffer, automatically increasing its capacity as needed.
The result of each append or insert is the StringBuilder itself, which allows a "chaining" style of calls, as in:
StringBuilder sb = new StringBuilder();
sb.append("My dog has ").append(fleaList.size()).append(" fleas (");
String separator = "";
for (Flea flea : fleaList) {
sb.append(separator).append(flea.getName());
separator = ", ";
}
String message = sb.append(").").toString();
System.out.println(message);
-- Main.joelneely - 18 Oct 2007
|