Building text is one of the most common jobs in any program: receipts, reports, log messages, web pages. Java gives you three tools for it. StringBuilder joins pieces efficiently, String.format and printf line numbers up neatly, and text blocks hold multi-line text without a mess of \n and quotes. This lesson shows when and how to use each.
In this lesson you will learn
- Why
+=on strings is slow inside loops StringBuilder:append,insert,reverse,delete- Format specifiers:
%s,%d,%.2f, widths and flags - Printing aligned tables with
printf - Text blocks,
formatted(),String.joinandrepeat
You should know Java strings and loops.
StringBuilder
A String can never change. Each s += "x" creates a completely new string and copies all the old characters into it. In a loop of 20,000 steps, that is a lot of copying. A StringBuilder keeps one growable buffer and adds to it in place.
public class Main {
public static void main(String[] args) {
// Strings are immutable: += builds a brand-new String every time
String s = "";
for (int i = 1; i <= 5; i++) {
s += i + " ";
}
System.out.println("With += : " + s);
// StringBuilder changes one buffer in place
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(' ');
}
System.out.println("StringBuilder : " + sb);
// Other useful StringBuilder methods
StringBuilder word = new StringBuilder("Dhaka");
word.insert(0, "City: ");
System.out.println(word);
word.reverse();
System.out.println(word);
word.reverse().setCharAt(6, 'd');
System.out.println(word + " (length " + word.length() + ")");
word.delete(0, 6);
System.out.println(word);
// Timing: build a 20,000-character string both ways
long t1 = System.nanoTime();
String slow = "";
for (int i = 0; i < 20_000; i++) slow += "x";
long t2 = System.nanoTime();
StringBuilder fast = new StringBuilder();
for (int i = 0; i < 20_000; i++) fast.append("x");
long t3 = System.nanoTime();
System.out.println("Same result? " + slow.equals(fast.toString()));
System.out.println("StringBuilder faster? " + ((t3 - t2) < (t2 - t1)));
}
}
Output
With += : 1 2 3 4 5
StringBuilder : 1 2 3 4 5
City: Dhaka
akahD :ytiC
City: dhaka (length 11)
dhaka
Same result? true
StringBuilder faster? true
appendreturns the same builder, so calls can be chained:sb.append(i).append(' ').insert,reverse,setCharAtanddelete(start, end)all change the builder itself.delete(0, 6)removes characters 0 to 5.- Printing a builder, or calling
toString(), gives an ordinaryString. - The timing test builds the same 20,000-character string both ways;
StringBuilderwins easily. For two or three pieces outside a loop, plain+is fine, because the compiler optimises it.
Formatting With String.format and printf
import java.util.List;
public class Main {
public static void main(String[] args) {
String name = "Nusrat";
double cgpa = 3.8167;
int credits = 96;
// String.format and printf use the same format codes
String line = String.format("%s has CGPA %.2f after %d credits", name, cgpa, credits);
System.out.println(line);
System.out.printf("%-10s|%8.1f|%5d|%n", name, cgpa, credits);
System.out.printf("%05d %,d %x %e%n", 42, 1234567, 255, 12345.678);
// A neat table with fixed column widths
List<String[]> rows = List.of(
new String[]{"Pen", "15", "3"},
new String[]{"Notebook", "120", "2"},
new String[]{"Calculator", "950", "1"});
System.out.printf("%-12s %6s %4s %8s%n", "Item", "Price", "Qty", "Total");
int grand = 0;
for (String[] r : rows) {
int price = Integer.parseInt(r[1]), qty = Integer.parseInt(r[2]);
grand += price * qty;
System.out.printf("%-12s %6d %4d %8d%n", r[0], price, qty, price * qty);
}
System.out.printf("%-12s %20d%n", "Grand total", grand);
// Text block (Java 15+) with formatted()
String receipt = """
Receipt for %s
Items: %d
Paid : %,d taka
""".formatted(name, rows.size(), grand);
System.out.print(receipt);
// String.join and repeat
System.out.println(String.join(" > ", "Home", "Courses", "Java"));
System.out.println("-".repeat(20));
}
}
Output
Nusrat has CGPA 3.82 after 96 credits
Nusrat | 3.8| 96|
00042 1,234,567 ff 1.234568e+04
Item Price Qty Total
Pen 15 3 45
Notebook 120 2 240
Calculator 950 1 950
Grand total 1235
Receipt for Nusrat
Items: 3
Paid : 1,235 taka
Home > Courses > Java
--------------------
| Specifier | Meaning | Example result |
|---|---|---|
%s | Any value as text | Nusrat |
%d | Whole number | 96 |
%.2f | Decimal with 2 places (rounded) | 3.82 |
%-10s | Width 10, left-aligned | “Nusrat “ |
%8.1f | Width 8, right-aligned, 1 decimal | ” 3.8″ |
%05d, %,d | Pad with zeros; thousands separator | 00042, 1,234,567 |
%x, %e | Hexadecimal; scientific notation | ff, 1.234568e+04 |
%n | New line for the current system |
String.formatreturns the text;System.out.printfprints it directly. They use the same codes.- Fixed widths line the table columns up: names left-aligned, numbers right-aligned so the digits sit under each other.
- A text block starts and ends with
""". Java removes the shared indentation, so the receipt prints without leading spaces..formatted(…)fills its%placeholders.
Common Mistakes
- Using
+=in a large loop. UseStringBuilderinstead. - Wrong specifier for the type.
%dwith adoublethrowsIllegalFormatConversionException. - Forgetting
%ninprintf. Unlikeprintln,printfdoes not add a new line by itself. - Comparing builders with
equals.StringBuilderdoes not compare contents; comparesb.toString()values instead.
Practice Exercises
Exercise 1. Use a StringBuilder to build the string "1-2-3-4-5" without a dash at the end.
Show answer
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
if (sb.length() > 0) sb.append('-');
sb.append(i);
}
System.out.println(sb); // 1-2-3-4-5
Adding the separator before every item except the first avoids a trailing dash. String.join or Collectors.joining do the same for collections.
Exercise 2. What does String.format("[%6.2f]", 3.14159) produce?
Show answer
[ 3.14]: width 6, two decimals, right-aligned, so two spaces are added before “3.14”.
Frequently Asked Questions
What is the difference between StringBuilder and StringBuffer?
StringBuffer is an older class whose methods are synchronized, so it is safe to share between threads but slower. StringBuilder is the faster choice for normal single-thread code.
Does printf round or cut off decimals?
It rounds. %.2f turns 3.8167 into 3.82. For money, do the rounding yourself with BigDecimal so you control exactly how it happens.
Summary
- Strings are immutable;
StringBuilderedits one buffer in place. String.formatandprintfuse%s,%d,%.2fwith widths and flags.- Negative widths left-align; positive widths right-align.
- Text blocks hold multi-line text;
formatted()fills their placeholders.
