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 is can be used:

int one = 1;
String color = "red";
StringBuilder sb = new StringBuilder();
sb.append("One=").append(one).append(", Color=").append(color).append('\n');
// Prints "One=1, Colour=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; i.e they provide methods for replacing and removing characters as well as adding them in various. The remining 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 a formatting an array of strings.

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

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

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

Feedback about page:

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

Table Of Contents