Course contentsShow
← Java
Lesson 2229 of 2,87043. String Handling in DepthFree lesson

Width and Alignment Specifiers

Using width specifications and alignment flags to control field width and justify output.

Width and Alignment Specifiers

What you'll learn: How to control the exact width of formatted output and justify text left, right, or center using format specifiers.

The Core Idea

When formatting strings, you often want output neatly aligned in columns of fixed width—like tables or reports. Java's formatting syntax lets you specify a minimum field width and choose alignment direction within that field. By default, numbers align right and strings align left, but you can override this behavior.

Width Specification

A width specifier is simply a number placed before the conversion character:

String.format("%10s", "hello");      // "     hello" (right-aligned, 10 chars wide)
String.format("%10d", 42);           // "        42" (right-aligned, 10 chars wide)

If the content is shorter than the specified width, Java pads it with spaces.

Alignment Flags

You control alignment with the minus sign (-) flag for left-alignment:

String.format("%-10s", "hello");     // "hello     " (left-aligned, 10 chars wide)
String.format("%-10d", 42);          // "42        " (left-aligned, 10 chars wide)

Practical Example

String header = String.format("%-15s %10s %10s", "Product", "Price", "Quantity");
String row1 = String.format("%-15s %10.2f %10d", "Widget", 29.99, 5);
String row2 = String.format("%-15s %10.2f %10d", "Gadget", 149.50, 2);

System.out.println(header);
System.out.println(row1);
System.out.println(row2);
// Product              Price   Quantity
// Widget              29.99          5
// Gadget             149.50          2

Notice how the left-aligned product names and right-aligned numbers create a clean, readable table.

Key Takeaway: Use width specifiers (like %10s) to reserve space and alignment flags (like %-10s) to control justification, creating professional, column-aligned output for reports and tables.