Careeroza
StringBuilder
A Mutable String
StringBuilder holds a resizable character buffer. append, insert, delete and reverse change the same object, so no new strings are created on every step.
Example
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);
sb.insert(0, ">> ");
System.out.println(sb);
sb.replace(3, 8, "Namaste");
System.out.println(sb);
sb.delete(0, 3);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
System.out.println("length = " + sb.length() + ", char at 0 = " + sb.charAt(0));
String result = sb.toString(); // back to an immutable String
System.out.println(result.getClass().getSimpleName());
}
}Output
Hello World >> Hello World >> Namaste World Namaste World dlroW etsamaN length = 13, char at 0 = d String
Building Text in a Loop
Example
Use StringBuilder whenever you build a string inside a loop.
public class Main {
public static void main(String[] args) {
int[] scores = { 78, 91, 66, 85 };
StringBuilder sb = new StringBuilder("Scores: [");
for (int i = 0; i < scores.length; i++) {
if (i > 0) sb.append(", ");
sb.append(scores[i]);
}
sb.append("]");
System.out.println(sb);
StringBuilder table = new StringBuilder();
for (int i = 1; i <= 3; i++) {
table.append("7 x ").append(i).append(" = ").append(7 * i).append(System.lineSeparator());
}
System.out.print(table);
}
}Output
Scores: [78, 91, 66, 85] 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21