Library contents

Java String.format

Build formatted text from a format string and a sequence of arguments.

A simple example

String.format

  1. Start with Text A, template [value]
  2. Do this Insert text between brackets
  3. Result "[A]"
Formatting keeps the brackets and fills the single space reserved for a value.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(String.format("[%s]", "A"));
    }
}
Output
[A]

Syntax

Java syntax
public static String format(String format, Object... args)
JDK 21 method signatures (2)
public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Print a zero-padded queue ticket

A printer receives badge or ticket data in separate fields. Use the display format required by the desk so names, numbers and separators occupy their intended places on the finished label.

ResultQ-007
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(String.format(java.util.Locale.ROOT, "Q-%03d", 7));
    }
}
Output
Q-007

A minimum width of three pads the number with zeros.

Advertisements

Show a measured weight to one decimal place

A parcel scale records more precision than the printed label can show. Format the measured weight to the specified number of decimal places without altering the underlying reading.

Result2.8 kg
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(String.format(java.util.Locale.ROOT, "%.1f kg", 2.75));
    }
}
Output
2.8 kg

The display rounds to one decimal place while the stored numeric value is unchanged.

Print the first entry tag

A coat-check desk numbers the first ticket one. The ticket printer includes the number as ordinary decimal text after a prefix. What does the completed label say?

GivenPrefix “Ticket ” + 1
Worked resultTicket 1

What to watch for

Choose a locale for machine-readable output. A conversion that is incompatible with its argument type throws an exception.

Documentation for String.format