Formatting And Text Blocks
Text blocks make multiline string literals readable, while printf controls alignment and numeric presentation.
A format such as %-10s left-aligns text in a column ten characters wide. %5.1f reserves five spaces for a decimal value with one digit after the point, and %n writes the platform line separator.
Line up a small report
public class Main {
public static void main(String[] args) {
String heading = """
ROOM TEMP
""";
System.out.print(heading);
System.out.printf("%-10s %5.1f%n", "Room A", 22.5);
System.out.printf("%-10s %5.1f%n", "Room B", 19.0);
}
}
Output:
ROOM TEMP
Room A 22.5
Room B 19.0
The heading comes from a text block. Java removes the indentation that every line of the block shares, so ROOM starts at the left edge. The block also ends with a line break because the closing """ sits on its own line, which is why the program uses print rather than println. The room names are left-aligned while the decimal temperatures are right-aligned.
Whole numbers
%d formats an integer. A number between % and d sets a minimum width, and the value is right-aligned inside it:
public class Main {
public static void main(String[] args) {
System.out.printf("Seats: %d%n", 42);
System.out.printf("[%4d]%n", 42);
System.out.printf("[%4d]%n", 1250);
}
}
Output:
Seats: 42
[ 42]
[1250]
The brackets show the width. 42 gets two spaces in front to fill four characters, and 1250 already fills them.
Formatting changes presentation, not the stored value. Keep calculations numeric and format only at the output boundary.
Now format a scoreboard with an eight-character column for each name and a three-character column for each score.