Java String.format: represent special characters in format strings
How Java String.format handles percent signs, line breaks, backslash escapes and Unicode, where each is processed, and where its output stops being safe or readable.
In Java, special characters in a String.format call pass through two separate layers. The compiler resolves backslash escapes in the string literal. At runtime, java.util.Formatter interprets percent-sign specifiers. Most confusion about special characters comes from treating these two layers as one. This review explains what each layer changes, when String.format is the right tool, and where its output can lose meaning or readability.
Is String.format the right tool for your text?
String.format suits human-readable messages, log lines and fixed-layout reports built from a template you control. Its main benefit is that the template stays separate from the values, and argument values are never reinterpreted as format syntax. The decisive tradeoff is that it escapes nothing for the destination. A quote, angle bracket, backslash or newline inside an argument is copied into the result unchanged.
Plain concatenation or a StringBuilder is often the better choice in three cases: the template contains many literal percent signs, the template text comes from users or external data, or you need no width, precision or number formatting at all. For JSON, HTML, SQL or shell commands, use a serializer, an encoder or a parameterized API instead of either approach.
What actually changes: compile-time escapes versus format specifiers
String.format does not alter characters you have already stored. It builds a new string from the template and the arguments. Before that happens, the compiler has already turned backslash escapes in the literal into real characters. By the time Formatter runs, no backslash sequences are left to interpret. The only character Formatter treats as special is the percent sign.
| Sequence in source | Handled by | Result |
| \n | Compiler | Line feed (U+000A) |
| \t | Compiler | Tab |
| " | Compiler | Double quote |
| \ | Compiler | One backslash |
| \s (Java 15 and later) | Compiler | Space; mainly useful in text blocks |
| \uXXXX | Compiler, before tokenizing | The UTF-16 code unit XXXX |
| %% | Formatter | One literal percent sign |
| %n | Formatter | The platform line separator |
// Backslash escapes are resolved by the compiler
String.format("Name:\t%s", name); // tab, then the value
String.format("Quote: \"%s\"", title); // literal double quotes
String.format("Folder: %s", "C:\\temp"); // prints C:\temp
// Percent signs and line separators are resolved by Formatter
String.format("Done: %d%%", 75); // "Done: 75%"
String.format("First%nSecond"); // OS line separator between lines
Unicode escapes have one trap of their own. The compiler translates \uXXXX before it splits the source into tokens. Writing \u000a inside a string literal therefore produces an actual line break in the middle of the literal, which fails to compile. Likewise, \u0022 ends the string early. Use \n and " for those characters, and keep \uXXXX for characters that have no shorter escape.
Percent signs and user-supplied text
A lone percent sign in a format string is parsed as the start of a specifier. Depending on what follows it, the call either throws an unchecked exception from the IllegalFormatException family or, worse, silently consumes an argument. For this reason, text you do not control must never be the format string. Pass it as an argument, or skip formatting for it entirely.
String userText = "Save 50% today";
String.format(userText); // throws at runtime: '%' starts a specifier
String.format("%s", userText); // safe: the text is only an argument
Characters beyond ASCII
The %c conversion accepts an int code point, so it can produce characters outside the Basic Multilingual Plane, such as emoji. In source code you can write non-ASCII characters directly or as \uXXXX escapes. Direct characters depend on the encoding javac uses to read the file. Since JDK 18 that default is UTF-8; in older JDKs it depended on the platform. Unicode escapes avoid the dependency at some cost to readability.
Width and precision count UTF-16 char units, not visible characters. An emoji outside the Basic Multilingual Plane counts as two units. A letter followed by a combining accent also counts as two. Padded columns that contain such text will look misaligned, even though the formatting is technically correct.
The documentation describes string precision as a maximum number of characters. If you truncate text that may contain surrogate pairs or combining marks, check how your JDK version handles a cut in the middle of one. The evidence for this review included no test results on that point.
String.format("%c", 0x1F600); // one emoji, stored as two UTF-16 chars
String.format("Caf\u00e9 %s", suffix); // é written as a Unicode escape
String.format("[%-4s]", "e\u0301"); // pads with 2 spaces; displays one column short
Other Java format syntaxes
String.formatted (Java 15 and later), printf and Formatter all follow the same rules as String.format. java.text.MessageFormat is a different system. It uses numbered placeholders such as {0} and does not treat percent signs as special. A single quote starts a quoted section in MessageFormat, so a literal apostrophe is written as two single quotes, and a literal brace is written inside quotes, as in '{'. Check which API a template is meant for before escaping it, because the two sets of rules conflict.
String json = """
{"name": "%s", "share": "%d%%"}
""".formatted(name, pct);
// name is inserted verbatim: a quote inside it breaks the JSON
Will the output stay readable after copying or sharing?
- Line endings: %n produces the operating system's separator, which is a carriage return plus line feed on Windows. For files or protocols that require one specific ending, write \n or \r\n explicitly.
- Locale: String.format without a Locale argument uses the default format locale, so decimals and digits can differ between machines. Pass Locale.ROOT for output that other programs will parse.
- Encoding: whether non-ASCII characters show up correctly in a console or log depends on the output stream's encoding and the viewer's font. String.format has no control over either.
- No context escaping: values are inserted literally, so output pasted into JSON, HTML or a command line may need separate escaping.
- Accessibility: assistive technology reads the characters that are actually stored. Box-drawing characters or decorative symbols used for layout may be announced by name or skipped. Provide a plain-text version when people may read the output through a screen reader.
String.format(Locale.ROOT, "%.2f", 1234.5); // "1234.50"
String.format(Locale.GERMANY, "%.2f", 1234.5); // "1234,50"
Gaps: the supplied evidence included no scoped tests of specific terminals, IDE consoles, chat tools or screen readers. The guidance above is based on documented Java language and Formatter behavior. Check rendering, copy and paste, and assistive-technology output in each destination you depend on.