Tsallaka zuwa abun ciki
Justice Tech School

StringBuilder and Formatting

StringBuilder builds text efficiently. String.format and printf use %s %d %f %n and width or precision such as %5.2f.

Example
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) sb.append(i).append(",");
sb.setLength(sb.length() - 1);
System.out.println(sb.reverse());
System.out.printf("%s has %d items costing %.2f%n", "cart", 3, 9.5);
System.out.println(String.format("|%5d|%-5s|", 42, "ab"));

Result

3,2,1
cart has 3 items costing 9.50
|   42|ab   |

Exercise

Efficient text builder.

new ()

Quiz Test

Why use StringBuilder in loops?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.