Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 201 ยท Strings

Formatting Strings

Format text in Java with String.format, formatted() and printf - width, flags, precision, argument indexes, dates - plus NumberFormat and Locale for any country.

Joining values with + works until you need control over how they look. A price should show exactly two decimals, a table needs columns that line up, a large number reads better as 1,250,000, and a German user expects 1.250.000,50 instead. Doing that by hand with concatenation is tedious and error-prone.

Java's format strings solve it. You write a template with placeholders such as %s and %.2f, and Java fills them in with your values, padded, rounded and aligned exactly as you asked. This lesson covers String.format, the newer formatted() method and printf, the full specifier syntax with flags, width and precision, dates, and finally Locale and NumberFormat for formatting numbers the way people in different countries expect.

Three ways to format

All three use the same template language. They differ only in where the result goes:

Method Returns Typical use
String.format(template, args...) a String building text to store or return
template.formatted(args...) a String the same, called on the template (Java 15+)
System.out.printf(template, args...) prints it quick formatted output
Java format, formatted and printf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each %... placeholder is a format specifier. The arguments fill them in order: the first argument goes into the first specifier, and so on. Two specifiers don't take an argument: %n inserts the platform's line separator, and %% inserts a literal percent sign. Unlike println, printf doesn't add a newline by itself, so end its template with %n. (Printing Output introduced printf briefly.)

Conversions: what kind of value

The letter at the end of a specifier is its conversion. It says what kind of value to expect and how to show it:

Specifier Formats Example Result
%s any value, via toString() "%s", "hi" hi
%S the same, in uppercase "%S", "hi" HI
%d integer (int, long, BigInteger) "%d", 42 42
%f decimal number "%f", 3.5 3.500000
%e scientific notation "%e", 12345.678 1.234568e+04
%x / %X hexadecimal integer "%x", 255 ff
%o octal integer "%o", 8 10
%c character "%c", 'A' A
%b boolean "%b", true true
%n line separator
%% a literal % %

Notice that %f shows six decimals by default. You'll almost always add a precision, as in %.2f.

The conversion must match the argument's type. Passing a double to %d doesn't round it; it throws an exception at run time, because the compiler doesn't check format strings:

Java When a format string is wrong

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because these errors only appear when the line runs, test every format string at least once. IDEs such as IntelliJ IDEA also highlight mismatched specifiers as you type.

The full specifier syntax

Between the % and the conversion letter you can add optional parts, always in this order:

TEXT
%[argument_index$][flags][width][.precision]conversion

   %1$-10.3s
    |  | | | +-- conversion: s
    |  | | +---- precision: 3
    |  | +------ width: 10
    |  +-------- flag: - (left-align)
    +----------- argument index: 1$ (the first argument)

You'll use width, precision and a few flags constantly; argument indexes occasionally.

Width and alignment

The width is the minimum number of characters the value takes. Shorter values are padded with spaces on the left (right-aligned). The - flag pads on the right instead (left-aligned). If a value is longer than the width, nothing is cut; it simply takes more room.

That's all you need to print tables with straight columns:

Java Lining up a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Text columns are usually left-aligned (%-18s) and number columns right-aligned (%9.2f), so the decimal points line up. Make the width of a heading match the width of the values below it.

Precision

The precision after the dot means different things for different conversions:

  • For %f and %e, it's the number of digits after the decimal point. The value is rounded (half up), not cut off.
  • For %s, it's the maximum number of characters: longer text is truncated.
  • For %d it isn't allowed at all; integers have no decimals.

Flags

Flags fine-tune the output:

Flag Effect Example Result
- left-align within the width "[%-6d]", 42 [42 ]
0 pad numbers with zeros "%05d", 42 00042
+ always show the sign "%+d", 42 +42
space a space before positive numbers "% d", 42 42
, group digits with the locale's separator "%,d", 1234567 1,234,567
( show negatives in parentheses "%(.2f", -8.5 (8.50)
# alternate form, e.g. 0x for hex "%#x", 255 0xff

You can combine flags: %+,.2f shows a sign, grouping and two decimals.

Java Precision and flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rounding line shows a subtlety: 1.005 prints as 1.01, even though the double closest to 1.005 is actually a hair below it. Java's formatter rounds the shortest decimal form of the number (the same digits Double.toString would show), which usually matches what people expect. For money calculations, though, don't rely on formatting to fix floating-point errors; use BigDecimal from BigInteger and BigDecimal.

Argument indexes

Normally specifiers consume arguments in order. Writing n$ right after the % picks argument number n (starting at 1), and %< reuses the previous one. This lets you use a value twice, or reorder values without changing the argument list, which translators sometimes need:

Java
String.format("%1$s, %2$s! Goodbye, %1$s.", "Sam", "welcome");
// "Sam, welcome! Goodbye, Sam."

String.format("%d in hex is %<x and in octal is %<o", 64);
// "64 in hex is 40 and in octal is 100"

Formatting dates and times

The t conversion formats dates and times, with a second letter for the part you want: %tY for the year, %tB for the month name, and so on. It works with java.time types like LocalDate and LocalDateTime. Since you usually need several parts of the same value, argument indexes or %< come in handy:

Java Dates with %t

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The most useful date parts:

Specifier Meaning Example
%tY / %ty year, 4 or 2 digits 2026 / 26
%tm month, 2 digits 10
%tB / %tb month name, full or short October / Oct
%td / %te day of month, with or without leading zero 09 / 9
%tA / %ta day of week, full or short Saturday / Sat
%tH / %tl hour, 24-hour or 12-hour 14 / 2
%tM / %tS minutes / seconds 05 / 30
%tp am or pm (%Tp for uppercase) pm
%tF ISO date, %tY-%tm-%td 2026-10-17
%tT time, %tH:%tM:%tS 14:05:30

%t is fine for quick output. For anything serious, such as user-facing dates, parsing, or custom patterns, DateTimeFormatter from Dates and Times is more powerful and reusable.

Locales: formatting for different countries

Countries write numbers differently. The US writes 1,234.56, Germany and Brazil write 1.234,56, and other regions use spaces or apostrophes between groups. A Locale object describes a language and region, and every formatting method has an overload that takes one as the first argument:

Java The same number in different locales

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Locale.of("pt", "BR") (Java 19+) creates a locale from a language and country code; older code uses new Locale("pt", "BR"), which is now deprecated. Constants such as Locale.US, Locale.GERMANY and Locale.FRANCE cover common cases.

Without a Locale argument, String.format uses the default locale of the machine. That's right for messages shown to the local user, but dangerous for data: on a German server, String.format("%.2f", 3.5) produces 3,50, which breaks CSV files, JSON and SQL. Pass Locale.ROOT whenever the output is meant for another program.

NumberFormat: numbers, money and percentages

String.format handles digits and separators, but not currency symbols, percentages or compact forms like "1.2K". For those, java.text.NumberFormat provides ready-made, locale-aware formatters:

Java NumberFormat for money, percentages and more

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The main factory methods are:

  • getNumberInstance(locale): grouped numbers with up to three decimals by default.
  • getCurrencyInstance(locale): the local currency symbol, position and decimal places. For Germany it puts the euro sign after the amount, 1.249,50 โ‚ฌ, joined by a non-breaking space (U+00A0) so the two never wrap onto separate lines. Keep that in mind if a test compares the result with a string literal typed with an ordinary space.
  • getPercentInstance(locale): multiplies by 100 and adds the percent sign.
  • getCompactNumberInstance(locale, style) (Java 12+): short forms like 2M or long forms like 2 million.

You can adjust any of them with setMinimumFractionDigits, setMaximumFractionDigits and setRoundingMode. For a fixed custom pattern, new DecimalFormat("#,##0.00") (a subclass) lets you spell out the shape directly.

NumberFormat objects are not thread-safe. Create one per use, or keep one per thread; don't share a single instance between threads that format at the same time. String.format has no such issue. Locales and Internationalization goes deeper into locale-aware formatting.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does String.format("[%6.2f]", 3.14159) return?

    Precision 2 gives "3.14" (4 characters), and width 6 pads it with two spaces on the left because numbers are right-aligned by default.
  2. 2. Which specifier prints the integer 7 as 007?

    The 0 flag pads with zeros up to the width of 3. %3d pads with spaces, and precision is not allowed for %d at all.
  3. 3. What happens when you run String.format("%d", 9.99)?

    The conversion must match the argument type. A double can't be formatted with %d, and the problem is only detected at run time.
  4. 4. What does String.format("%-5s|%.3s", "ab", "abcdef") return?

    %-5s left-aligns "ab" in 5 characters, and precision 3 on a string truncates "abcdef" to "abc".
  5. 5. Your program writes a CSV file of prices. Which call is safest?

    Without a locale, the machine's default is used, which could write commas as decimal separators. Locale.ROOT always gives a dot, so other programs can read the file.

Summary

  • String.format(...) and "template".formatted(...) return formatted text; printf prints it. End printf templates with %n.
  • A specifier is %[index$][flags][width][.precision]conversion. Common conversions: %s, %d, %f, %x, %c, %b, %n, %%.
  • Width pads to a minimum size (right-aligned; - left-aligns). Precision sets decimals for %f (rounded) and the maximum length for %s.
  • Flags: 0 zero-pads, + shows signs, , groups digits, ( wraps negatives, # adds prefixes like 0x.
  • Type mismatches and missing arguments throw at run time, so test every format string.
  • %t formats dates (%tF, %tT, %tB...); prefer DateTimeFormatter for serious work.
  • Pass a Locale for user-facing numbers and Locale.ROOT for machine-readable output. NumberFormat adds currency, percent and compact number formats.

Next: Text Blocks and Escape Sequences, where you'll write multi-line strings for JSON, SQL and HTML without a forest of \n and \".