Library contents

Java String.formatted

Use a string itself as the format template and supply values for its placeholders.

A simple example

String.formatted

  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("[%s]".formatted("A"));
    }
}
Output
[A]

Syntax

Java syntax
public String formatted(Object... args)
JDK 21 method signatures (1)
public String formatted(Object... args)
Run these examples in Java

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

java Main.java

Print a student and course on one label

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.

ResultAda — Biology
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("%s — %s".formatted("Ada", "Biology"));
    }
}
Output
Ada — Biology

Each string fills the next placeholder in the template.

Advertisements

Show a literal percent sign in a notice

A printed notice must display a percentage and uses a formatter that treats the percent sign specially. Escape the literal mark in the format string so it survives the formatting step.

ResultAttendance target: 90%
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("Attendance target: %s%%".formatted("90"));
    }
}
Output
Attendance target: 90%

The doubled percent sign prints one literal percent sign.

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

formatted uses the default formatting locale. Use String.format with an explicit locale when locale-sensitive output must be reproducible.

Documentation for String.formatted