Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.format — formatting text

String.format builds text from a format string and arguments using specifiers such as %s, %d, and %.2f. An explicit Locale makes numeric formatting independent of the environment's default locale settings.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

String.format(String format, Object... args)
String.format(Locale l, String format, Object... args)
%[argument_index$][flags][width][.precision]conversion

String.format is a static method that returns a formatted String; it does not print the result itself. The format string combines ordinary text with specifiers defined by Formatter. Arguments follow the format string as Object... args.

The overload String.format(String format, Object... args) uses Locale.getDefault(Locale.Category.FORMAT). The variant String.format(Locale l, String format, Object... args) lets you specify the locale explicitly; null means no localization. The example uses Locale.US so the decimal separator is a dot.

For common conversions, the syntax is %[argument_index$][flags][width][.precision]conversion. %s formats an argument's string representation, %d a decimal integer, and %.2f a floating-point number with two digits after the decimal separator. %04d sets a minimum width of four characters with zero padding. %2$s selects the second argument. %% inserts a literal % without consuming an argument; %n inserts the platform-specific line separator.

An invalid format string, incompatible type, or missing required argument causes IllegalFormatException. For example, %d does not accept a String containing digits. Extra arguments are ignored, and handling of null values depends on the conversion. Keep control of the format string and pass variable data as arguments.

Examples

import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String result = String.format(
            Locale.US, "%s | id=%04d | score=%.2f | %d%%",
            "Ada", 7, 12.5, 80
        );
        System.out.print(result);
    }
}

Result

Ada | id=0007 | score=12.50 | 80%

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources