Comparing StringBuffer StringBuilder Formatter and StringJoiner

suggest change

The StringBuffer, StringBuilder, Formatter and StringJoiner classes are Java SE utility classes that are primarily used for assembling strings from other information:

This example shows how StringBuilder can be used:

int one = 1;
String color = "red";
StringBuilder sb = new StringBuilder();
sb.append("One=").append(one).append(", Color=").append(color).append('\n');
System.out.print(sb);
// Prints "One=1, Color=red" followed by an ASCII newline.

(The StringBuffer class is used the same way: just change StringBuilder to StringBuffer in the above)

The StringBuffer and StringBuilder classes are suitable for both assembling and modifying strings; that is, they provide methods for replacing and removing characters as well as adding them. The remaining two classes are specific to the task of assembling strings.

Here are some typical examples of Formatter usage:

// This does the same thing as the StringBuilder example above
int one = 1;
String color = "red";
Formatter f = new Formatter();
System.out.print(f.format("One=%d, colour=%s%n", one, color));
// Prints "One=1, colour=red" followed by the platform's line separator

// The same thing using the `String.format` convenience method
System.out.print(String.format("One=%d, color=%s%n", one, color));

The StringJoiner class is not ideal for the above task, so here is an example of formatting an array of strings.

StringJoiner sj = new StringJoiner(", ", "[", "]");
for (String s : new String[]{"A", "B", "C"}) {
    sj.add(s);
}
System.out.println(sj);
// Prints "[A, B, C]"

The use-cases for the 4 classes can be summarized:

- parsing the `format` string,
- creating and populating a *varargs* array, and
- autoboxing any primitive type arguments.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents