Reading history

Java StringBuilder and String Formatting

5 min read 0 views

Build text efficiently in Java with StringBuilder, format numbers and tables with String.format and printf, and write multi-line text blocks.

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.join and repeat

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
  • append returns the same builder, so calls can be chained: sb.append(i).append(' ').
  • insert, reverse, setCharAt and delete(start, end) all change the builder itself. delete(0, 6) removes characters 0 to 5.
  • Printing a builder, or calling toString(), gives an ordinary String.
  • The timing test builds the same 20,000-character string both ways; StringBuilder wins 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
--------------------
SpecifierMeaningExample result
%sAny value as textNusrat
%dWhole number96
%.2fDecimal with 2 places (rounded)3.82
%-10sWidth 10, left-aligned“Nusrat    “
%8.1fWidth 8, right-aligned, 1 decimal”     3.8″
%05d, %,dPad with zeros; thousands separator00042, 1,234,567
%x, %eHexadecimal; scientific notationff, 1.234568e+04
%nNew line for the current system
  • String.format returns the text; System.out.printf prints 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

  1. Using += in a large loop. Use StringBuilder instead.
  2. Wrong specifier for the type. %d with a double throws IllegalFormatConversionException.
  3. Forgetting %n in printf. Unlike println, printf does not add a new line by itself.
  4. Comparing builders with equals. StringBuilder does not compare contents; compare sb.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; StringBuilder edits one buffer in place.
  • String.format and printf use %s, %d, %.2f with widths and flags.
  • Negative widths left-align; positive widths right-align.
  • Text blocks hold multi-line text; formatted() fills their placeholders.

Next: Java Varargs and Method Overloading.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *