Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Comparing StringBuffer, StringBuilder, Formatter and StringJoiner
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 number = 42; String shade = "blue"; StringBuilder newBuilder = new StringBuilder(); newBuilder.append("Number=").append(number).append(", Shade=").append(shade).append('\n'); System.out.print(newBuilder); // Prints "Number=42, Shade=blue" 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:
int number = 42; String carBrand = "BMW"; Formatter f = new Formatter(); System.out.print(f.format("Number=%d, brand=%s%n", number, carBrand)); // Prints "Number=42, Brand=BMW" followed by the platform's line separator // The same thing using the `String.format` convenience method System.out.print(String.format("Number=%d, brand=%s%n", number, carBrand));
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[]{"Apple", "Banana", "Cherry"}) { sj.add(s); } System.out.println(sj); // Prints "<Apple | Banana | Cherry>"
Here are some typical examples of Formatter usage:
Problem : Create a String containing n repetitions of a String s.
The trivial approach would be repeatedly concatenating the String
final int n = ... final String s = ... String result = ""; for (int i = 0; i < n; i++) { result += s; }
This creates n new string instances containing 1 to n repetitions of s resulting in a runtime of O(s.length() * n²) = O(s.length() * (1+2+...+(n-1)+n)).
To avoid this StringBuilder should be used, which allows creating the String in O(s.length() * n) instead:
final int n = ... final String s = ... StringBuilder builder = new StringBuilder(); for (int i = 0; i < n; i++) { builder.append(s); } String result = builder.toString();
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions