String.format and printf

A format string is a template with placeholders, and the arguments fill them in order. String.format returns the text and printf writes it, and both read the same placeholders: a conversion letter, an optional width, an optional precision and flags for alignment, signs and grouping.

String.format

%s takes any value and calls its toString, %d takes an integer, %f takes a floating-point number and %% writes a percent sign. A wrong type is a run-time exception, not a compile error, because the arguments are just Object values.

The file Format.java:

public class Format { public static void main(String[] args) { String name = "Ada"; int count = 3; double price = 12.5; System.out.println(String.format("name=%s count=%d", name, count)); System.out.println(String.format("price=%.2f", price)); System.out.println(String.format("|%10s|%-10s|", name, name)); System.out.println(String.format("%,d", 1234567)); System.out.println(String.format("%05d", 42)); System.out.printf("%s has %d items%n", name, count); } }

javac -Xlint:all Format.java
java Format

name=Ada count=3
price=12.50
| Ada|Ada |
1,234,567
00042
Ada has 3 items

%.2f rounds to two decimals and keeps the trailing zero, which a plain println(price) would drop. %,d groups thousands with the separator of the locale, and %05d pads with zeros to five characters.

Width, alignment and padding

The number before the conversion is the minimum width, and the text is padded with spaces on the left. A minus sign before the width pads on the right, which is what a left-aligned column needs. The pipes in the output above show both: %10s put Ada at the right edge of ten characters, and %-10s put it at the left.

A precision on a string, as in %.3s, truncates it; on a number it sets the number of digits after the point. The two may be combined, as in %8.2f, which is a column eight wide with two decimals.

A text table

A table is one format string per row, with the same widths everywhere. The first row uses strings for the headings, the other rows use %d and %f, and the same template keeps the columns aligned without a single tab.

public class Table { public static void main(String[] args) { System.out.printf("%-10s %5s %8s%n", "item", "qty", "price"); System.out.printf("%-10s %5d %8.2f%n", "apple", 3, 0.5); System.out.printf("%-10s %5d %8.2f%n", "bread", 1, 2.25); System.out.printf("%-10s %5d %8.2f%n", "cheese", 2, 7.99); } }

javac -Xlint:all Table.java
java Table

item qty price
apple 3 0.50
bread 1 2.25
cheese 2 7.99

The heading row passes strings to %5s and %8s, and the data rows pass numbers to the same widths. A name longer than ten characters would push its row out of alignment, which is why a formatter that must handle any text measures the longest value before it chooses the width.

printf and %n

System.out.printf writes the formatted text without a newline of its own, so the format must end with one: %n is the platform line separator, and public class Printf { public static void main(String[] args) { System.out.printf("%d + %d = %d%n", 2, 3, 5); String line = String.format("%.1f%%", 42.0); System.out.println(line); System.out.println(String.format("%,.2f", 1234.5678)); } }

javac -Xlint:all Printf.java
java Printf

2 + 3 = 5
42.0%
1,234.57

%% is how a literal percent sign is written, because a lone % starts a conversion. The last line combines grouping and precision: the number is rounded to two decimals and then grouped, which is the order a price column needs.

The locale

The grouping separator and the decimal point come from the default locale of the JVM, and the same format can therefore give different text on another machine. An overload takes the locale explicitly, which is what a program that parses its own output must do.

import java.util.Locale; public class LocaleDemo { public static void main(String[] args) { System.out.println(String.format(Locale.GERMANY, "%,.2f", 1234.5678)); System.out.println(String.format(Locale.US, "%,.2f", 1234.5678)); } }

javac -Xlint:all LocaleDemo.java
java LocaleDemo

1.234,57
1,234.57

Germany groups with a point and writes the decimal comma; the United States does the opposite. The default on this machine is en_US, which is why the earlier output has the comma grouping. Lesson 111 covers dates and numbers with NumberFormat and Locale in more detail.

Exercises

  1. Print the number 7 as a three-character field, first right-aligned and then left-aligned.
  2. Format 3.14159 with two, four and six decimals in one program.
  3. Add a fourth item to the table in Table.java with a name longer than ten characters and see how the alignment breaks.
  4. Format the same number with Locale.FRANCE and with Locale.US and compare the separators.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which conversion writes an integer?

    Answer

    %d

    %d is the decimal integer conversion; %f is for floating-point values.

  2. What does %.2f do to 12.5?

    Answer

    Writes 12.50 with two decimals

    The precision sets the digits after the point, and the missing digit is filled with zero.

  3. What does a minus before the width, as in %-10s, do?

    Answer

    Pads on the right, so the text is left-aligned

    A positive width pads on the left; the minus flag flips the padding to the right.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println(String.format("%s=%d", "n", 42)); } }

    Answer

    n=42

    %s writes the string and %d the integer, in the order of the arguments.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println(String.format("[%5d]", 42)); } }

    Answer

    [ 42]

    A width of five pads with spaces on the left, giving three spaces before 42.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.printf("%d%n", 7); System.out.println("done"); } }

    Answer

    7 / done

    %n ends the line, so the two writes are on separate lines.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println(String.format("%,d", 1000000)); } }

    Answer

    1,000,000

    The grouping flag adds the separator of the default locale, which is a comma in en_US.

  8. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(String.format("%.1f%%", 25.0)); } }

    Answer

    25.0%

    The precision keeps one decimal and %% writes a literal percent sign.

  9. What happens when the argument type does not match the conversion?

    Answer

    The format call throws an exception at run time

    The arguments are Objects, so the mismatch can only be found when the format string is applied.

  10. Why pass a Locale explicitly to String.format?

    Answer

    The separators otherwise depend on the default locale of the JVM

    Grouping and decimal separators are locale data, so a fixed locale makes the output reproducible.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev