MessageFormat and ChoiceFormat in Java: Placeholders, Plurals and Choices
Building translatable sentences with java.text.MessageFormat: numbered placeholders with number, date and java.time styles, quoting rules, ChoiceFormat for counts and ranges and its limits for real plural rules, ListFormat (Java 22) and the list, compact and dtf pattern types added in Java 23.
kvi5hnuCode Sprout team member10 min readOn this page
A program that builds sentences by concatenation, such as "Deleted " + n + " files", cannot be translated. Another language may need the number in a different position, a different word order, or a different noun form depending on the number. java.text.MessageFormat solves the first two problems: the whole sentence lives in one pattern string that a translator can rearrange, and the values are inserted at numbered placeholders with locale-aware formatting. ChoiceFormat handles simple choices based on numbers, and ListFormat (Java 22) joins lists the way each language does.
Placeholders
A message pattern is ordinary text with placeholders {0}, {1}, ... that refer to arguments by index:
String msg = MessageFormat.format(
"On {2}, a {0} destroyed {1} houses and caused {3} of damage.",
"hurricane", 99, date, 1.0E8);
// On 1/1/99, 12:00 AM, a hurricane destroyed 99 houses and caused 100,000,000 of damage.
The static format(String, Object...) is a convenient varargs method. Each argument is formatted according to its type: numbers with a NumberFormat, java.util.Date with a DateFormat, strings as they are, anything else with toString(). Because placeholders are numbered, a translation can use them in any order and even repeat them:
{0} zerstörte am {2,date,long} {1} Häuser und richtete einen Schaden von {3,number,currency} an.
Format types and styles
A placeholder can carry a format type and a format style, separated by commas: {index,type,style}.
| Type | Styles | Example output (en-US) |
|---|---|---|
number | (none), integer, currency, percent, compact_short, compact_long (Java 23), or a DecimalFormat pattern | 1,234,567.891, 1,234,568, $100,000,000.00, 26%, 1M, 1 million, 1,234,567.9 with #,##0.0 |
date, time | short, medium, long, full, or a SimpleDateFormat pattern | 1/1/99, January 1, 1999, 1999-01-01 |
dtf_date, dtf_time, dtf_datetime (Java 23) | short, medium, long, full, or a DateTimeFormatter pattern | July 20, 1969, 1969-07-21 02:56 |
a predefined DateTimeFormatter name (Java 23) | none | {0,ISO_LOCAL_DATE} gives 1969-07-20 |
list (Java 23) | (none), or, unit | Armstrong, Aldrin, and Collins |
choice | a ChoiceFormat pattern | see below |
Types and styles are case-insensitive. Two things trip people up:
- The
dateandtimetypes work only withjava.util.Date. Passing aLocalDateto{0,date,long}throwsIllegalArgumentException. Before Java 23 you had to convert or pre-format java.time values; since Java 23 usedtf_date,dtf_time,dtf_datetimeor a formatter name such asISO_LOCAL_DATE. - Plain
{0}formats numbers with grouping.{0}with 2025 prints2,025, which is wrong for years, IDs and port numbers. Use{0,number,#}or pass the value as a string.
Using a specific locale
The static MessageFormat.format uses the default locale (FORMAT category). For any other locale, create an instance; there is no varargs format method on instances, so wrap the arguments in an array:
var formatter = new MessageFormat(pattern, Locale.GERMANY);
String text = formatter.format(new Object[] { "Ein Wirbelsturm", 99, date, 1.0E8 });
The locale must be given in the constructor, or set with setLocale before applyPattern, because the subformats are created when the pattern is parsed. Reuse the instance for repeated messages; like the other java.text formats it is not thread-safe.
Instances can do more than the static method: toPattern() returns the pattern, getFormatsByArgumentIndex() and setFormatByArgumentIndex(i, format) inspect or replace subformats (for instance, to plug in a DateTimeFormatter.toFormat() on older Java versions), and parse(String) turns formatted text back into an Object[].
Quoting
Braces and apostrophes have special meaning in patterns:
| Pattern | Output | Why |
|---|---|---|
A {0} is in '{' and '}' | A block is in { and } | text between single quotes is literal |
It''s {0}''s turn | It's Ada's turn | '' is one apostrophe |
It's {0}'s turn | Its {0}s turn | the single quotes start and end a quoted section, so {0} is not replaced |
<a href=''{0}''>{1}</a> | <a href='/home'>Home</a> | doubled quotes around a placeholder |
{0}’s turn (U+2019) | Ada’s turn | a typographic apostrophe is not special |
The single apostrophe is the most common localization bug with MessageFormat, especially in French and Italian, where apostrophes are everywhere. Tell translators which strings go through MessageFormat, or encourage the typographically correct ’, which needs no escaping.
Choice formats
Consider {1} houses again. With one house the sentence reads "1 houses". A choice format selects a text depending on a number. It is a list of limit/text pairs separated by |, where # separates each limit from its text:
{0,choice,0#no houses|1#one house|2#{0,number,integer} houses}

Each limit starts an interval that runs until the next limit. A value selects the text of the last limit it reaches, and values below the first limit also select the first text, so -1 gives "no houses". A text may contain placeholders again: the chosen string is fed back into the MessageFormat, which is why {0} appears inside the choice.
| Value | Result |
|---|---|
| -1, 0 | no houses |
| 1 | one house |
| 2 | 2 houses |
| 1500 | 1,500 houses |
The separators come in three spellings: # or ≤ (U+2264) means "at least this limit", < means "strictly greater than this limit", and ∞ (U+221E) can be written for infinity, as in -∞<negative|0≤none|0<fraction|1#one file|1<{0,number,integer} files. That pattern distinguishes 0, values strictly between 0 and 1, exactly 1, and more than 1.
ChoiceFormat is also usable on its own, with arrays of limits and strings:
var grade = new ChoiceFormat(new double[] {0, 60, 70, 80, 90},
new String[] {"F", "D", "C", "B", "A"});
grade.format(85); // B
Its static helpers nextDouble(d) and previousDouble(d) return the adjacent double values, which is how < limits are implemented internally.
Why choice formats are not enough for plurals
English needs two forms (1 file, 2 files). Other languages need different numbers of forms based on rules that ranges cannot express. Russian uses one form for 1, 21, 31, ... (but not 11), another for 2–4, 22–24, ..., and a third for 5–20, 25–30, .... A choice pattern can only split the number line into intervals, so it gets 21 wrong:
1 -> 1 файл, 2 -> 2 файла, 5 -> 5 файлов, 21 -> 21 файлов (should be 21 файл)
The CLDR plural rules (categories zero, one, two, few, many, other) solve this properly. The JDK uses them internally for CompactNumberFormat, but MessageFormat has no plural type. If you need correct plurals in many languages, use ICU4J's com.ibm.icu.text.MessageFormat, which supports {n, plural, one{# file} few{# файла} other{# files}} and select for gender, or restructure the message to avoid the problem (Files: 21).
Lists with ListFormat
Joining items is locale-dependent too: English uses a serial comma and "and", German has no comma before "und", Japanese uses 、. java.text.ListFormat (Java 22) does it with CLDR data:
ListFormat.getInstance(Locale.US, ListFormat.Type.STANDARD, ListFormat.Style.FULL)
.format(List.of("Armstrong", "Aldrin", "Collins")); // Armstrong, Aldrin, and Collins
| Locale | STANDARD | OR |
|---|---|---|
| en-US | Armstrong, Aldrin, and Collins | Armstrong, Aldrin, or Collins |
| de-DE | Armstrong, Aldrin und Collins | Armstrong, Aldrin oder Collins |
| fr-FR | Armstrong, Aldrin et Collins | Armstrong, Aldrin ou Collins |
| ja-JP | Armstrong、Aldrin、Collins | Armstrong、Aldrin、またはCollins |
Type.UNIT is for measurements (3 ft, 7 in), and Style.SHORT and Style.NARROW give shorter connectors. A ListFormat can parse its own output back into a list, and in a message pattern you write {0,list}, {0,list,or} or {0,list,unit} (Java 23).
The program
The demo sets the default locale and time zone so the static format method is deterministic, then goes through placeholders, styles, java.time types, lists, quoting rules, choice formats, the Russian plural problem, parsing, and common mistakes.
import java.text.*;
import java.time.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws ParseException {
Locale.setDefault(Locale.US); // MessageFormat.format(String, Object...) uses the default
ZoneId utc = ZoneId.of("UTC");
TimeZone.setDefault(TimeZone.getTimeZone(utc));
Date day = Date.from(LocalDate.of(1999, 1, 1).atStartOfDay(utc).toInstant());
System.out.println("== Basic placeholders ==");
System.out.println(v(MessageFormat.format(
"On {2}, a {0} destroyed {1} houses and caused {3} of damage.",
"hurricane", 99, day, 1.0E8)));
System.out.println(MessageFormat.format(
"On {2,date,long}, a {0} destroyed {1} houses and caused {3,number,currency} of damage.",
"hurricane", 99, day, 1.0E8));
System.out.println(MessageFormat.format("Year {0} vs {0,number,#}", 2025));
System.out.println("\n== The same arguments in another locale ==");
String de = "{0} zerstörte am {2,date,long} {1} Häuser und richtete einen Schaden von {3,number,currency} an.";
MessageFormat germanFormat = new MessageFormat(de, Locale.GERMANY);
System.out.println(v(germanFormat.format(new Object[] {"Ein Wirbelsturm", 99, day, 1.0E8})));
System.out.println("\n== Number and date styles ==");
MessageFormat styles = new MessageFormat(
"{0,number} | {0,number,integer} | {1,number,percent} | {0,number,#,##0.0} | {0,number,compact_short} | {0,number,compact_long}",
Locale.US);
System.out.println(styles.format(new Object[] {1234567.891, 0.256}));
MessageFormat dates = new MessageFormat(
"{0,date,short} | {0,date,medium} | {0,date,yyyy-MM-dd} | {0,time,HH:mm}", Locale.US);
System.out.println(dates.format(new Object[] {day}));
System.out.println("\n== java.time arguments (Java 23) ==");
LocalDate landing = LocalDate.of(1969, 7, 20);
LocalDateTime step = LocalDateTime.of(1969, 7, 21, 2, 56);
MessageFormat modern = new MessageFormat(
"{0,dtf_date,long} | {0,ISO_LOCAL_DATE} | {1,dtf_datetime,yyyy-MM-dd HH:mm} | {1,dtf_time,short}",
Locale.US);
System.out.println(v(modern.format(new Object[] {landing, step})));
try {
MessageFormat.format("{0,date,long}", landing);
} catch (IllegalArgumentException e) {
System.out.println("{0,date} with a LocalDate -> IllegalArgumentException");
}
System.out.println("\n== Lists (Java 22 ListFormat, Java 23 pattern support) ==");
List<String> crew = List.of("Armstrong", "Aldrin", "Collins");
for (Locale loc : List.of(Locale.US, Locale.GERMANY, Locale.FRANCE, Locale.JAPAN)) {
System.out.println(loc + ": " + ListFormat.getInstance(loc, ListFormat.Type.STANDARD, ListFormat.Style.FULL)
.format(crew) + " / " + ListFormat.getInstance(loc, ListFormat.Type.OR, ListFormat.Style.FULL)
.format(crew));
}
System.out.println(new MessageFormat("Crew: {0,list}. Pick {1,list,or}.", Locale.US)
.format(new Object[] {crew, crew.subList(0, 2)}));
System.out.println("UNIT/NARROW: " + ListFormat.getInstance(Locale.US, ListFormat.Type.UNIT,
ListFormat.Style.NARROW).format(List.of("3 ft", "7 in")));
System.out.println("parse: " + ListFormat.getInstance().parse("Armstrong, Aldrin, and Collins"));
System.out.println("\n== Quoting ==");
System.out.println(MessageFormat.format("A {0} is enclosed in '{' and '}'", "block"));
System.out.println(MessageFormat.format("It''s {0}''s turn", "Ada"));
System.out.println(MessageFormat.format("It's {0}'s turn", "Ada"));
System.out.println(MessageFormat.format("<a href=''{0}''>{1}</a>", "/home", "Home"));
System.out.println(MessageFormat.format("{0}’s curly apostrophe needs no escaping", "Ada"));
System.out.println("\n== Choice formats ==");
MessageFormat houses = new MessageFormat(
"{0,choice,0#no houses|1#one house|2#{0,number,integer} houses}", Locale.US);
for (int n : new int[] {-1, 0, 1, 2, 1500})
System.out.printf("%5d -> %s%n", n, houses.format(new Object[] {n}));
MessageFormat files = new MessageFormat(
"{0,choice,-∞<negative|0≤none|0<{0,number,0.#} (fraction)|1#one file|1<{0,number,integer} files}",
Locale.US);
for (double d : new double[] {-3, 0, 0.5, 1, 7})
System.out.printf("%5s -> %s%n", d, files.format(new Object[] {d}));
ChoiceFormat grade = new ChoiceFormat(new double[] {0, 60, 70, 80, 90},
new String[] {"F", "D", "C", "B", "A"});
System.out.println("grades: " + grade.format(59.9) + grade.format(60) + grade.format(85) + grade.format(100));
System.out.println("pattern: " + grade.toPattern());
System.out.println("nextDouble(1.0) = " + ChoiceFormat.nextDouble(1.0));
System.out.println("\n== Plurals beyond English ==");
MessageFormat ru = new MessageFormat(
"{0,choice,0#нет файлов|1#{0} файл|2#{0} файла|5#{0} файлов}", Locale.forLanguageTag("ru"));
for (int n : new int[] {1, 2, 5, 21, 22})
System.out.println(n + " -> " + ru.format(new Object[] {n}));
System.out.println("\n== Reusing and parsing ==");
MessageFormat reusable = new MessageFormat("{0} scored {1,number,integer} points", Locale.US);
System.out.println(reusable.toPattern());
Object[] parsed = reusable.parse("Ada scored 1,250 points");
System.out.println("parsed: " + parsed[0] + " / " + parsed[1] + " (" + parsed[1].getClass().getSimpleName() + ")");
System.out.println("formats: " + reusable.getFormatsByArgumentIndex().length
+ " args, second is " + reusable.getFormatsByArgumentIndex()[1].getClass().getSimpleName());
System.out.println("\n== Common mistakes ==");
System.out.println(MessageFormat.format("{0} items", 1234));
System.out.println(MessageFormat.format("ID {0,number,#}", 1234));
System.out.println(MessageFormat.format("Missing {1} and {0}", "only-one"));
}
static String v(String s) {
return s.replace("\u202f", "<NNBSP>").replace("\u00a0", "<NBSP>");
}
}
== Basic placeholders ==
On 1/1/99, 12:00<NNBSP>AM, a hurricane destroyed 99 houses and caused 100,000,000 of damage.
On January 1, 1999, a hurricane destroyed 99 houses and caused $100,000,000.00 of damage.
Year 2,025 vs 2025
== The same arguments in another locale ==
Ein Wirbelsturm zerstörte am 1. Januar 1999 99 Häuser und richtete einen Schaden von 100.000.000,00<NBSP>€ an.
== Number and date styles ==
1,234,567.891 | 1,234,568 | 26% | 1,234,567.9 | 1M | 1 million
1/1/99 | Jan 1, 1999 | 1999-01-01 | 00:00
== java.time arguments (Java 23) ==
July 20, 1969 | 1969-07-20 | 1969-07-21 02:56 | 2:56<NNBSP>AM
{0,date} with a LocalDate -> IllegalArgumentException
== Lists (Java 22 ListFormat, Java 23 pattern support) ==
en_US: Armstrong, Aldrin, and Collins / Armstrong, Aldrin, or Collins
de_DE: Armstrong, Aldrin und Collins / Armstrong, Aldrin oder Collins
fr_FR: Armstrong, Aldrin et Collins / Armstrong, Aldrin ou Collins
ja_JP: Armstrong、Aldrin、Collins / Armstrong、Aldrin、またはCollins
Crew: Armstrong, Aldrin, and Collins. Pick Armstrong or Aldrin.
UNIT/NARROW: 3 ft 7 in
parse: [Armstrong, Aldrin, Collins]
== Quoting ==
A block is enclosed in { and }
It's Ada's turn
Its {0}s turn
<a href='/home'>Home</a>
Ada’s curly apostrophe needs no escaping
== Choice formats ==
-1 -> no houses
0 -> no houses
1 -> one house
2 -> 2 houses
1500 -> 1,500 houses
-3.0 -> negative
0.0 -> none
0.5 -> 0.5 (fraction)
1.0 -> one file
7.0 -> 7 files
grades: FDBA
pattern: 0.0#F|60.0#D|70.0#C|80.0#B|90.0#A
nextDouble(1.0) = 1.0000000000000002
== Plurals beyond English ==
1 -> 1 файл
2 -> 2 файла
5 -> 5 файлов
21 -> 21 файлов
22 -> 22 файлов
== Reusing and parsing ==
{0} scored {1,number,integer} points
parsed: Ada / 1250 (Long)
formats: 2 args, second is DecimalFormat
== Common mistakes ==
1,234 items
ID 1234
Missing {1} and only-one
Common questions
Why does my message print {0} instead of the value, or lose its apostrophe?
A single apostrophe starts a quoted section, so It's {0} prints Its {0}. Write It''s {0} in every pattern that goes through MessageFormat, or use the typographic ’.
MessageFormat or String.format?
MessageFormat for user-facing text that gets translated: numbered placeholders can be reordered, and values are formatted for the locale. String.format (or formatted) for logs and technical output, where %s order is fixed.
Can MessageFormat format LocalDate and other java.time values?
Since Java 23, yes, but not with the date and time types, which still accept only java.util.Date and throw IllegalArgumentException for a LocalDate. Use the dtf_date, dtf_time and dtf_datetime types ({0,dtf_date,long}) or a predefined formatter name ({0,ISO_LOCAL_DATE}). On older versions, format the value yourself first, or set a subformat with DateTimeFormatter.toFormat().
How do I handle plurals properly in many languages?
ChoiceFormat handles languages whose rules are ranges, like English. For Slavic, Arabic and others, use ICU4J's MessageFormat with plural or keep separate keys per plural category and select one with your own CLDR-based logic.
Is MessageFormat thread-safe?
No. Create one per use, which is cheap enough for most messages, or one per thread. The static MessageFormat.format creates a fresh instance each call.
API reference
| Method | Purpose |
|---|---|
MessageFormat.format(String pattern, Object... args) | one-off formatting with the default locale |
new MessageFormat(String pattern[, Locale]) | reusable formatter |
format(Object[] args), format(Object, StringBuffer, FieldPosition) | format with an instance |
applyPattern, toPattern, setLocale, getLocale | pattern and locale |
getFormatsByArgumentIndex, setFormatByArgumentIndex | inspect or replace subformats |
parse(String) | parse formatted text into arguments |
new ChoiceFormat(String), new ChoiceFormat(double[], String[]) | choice format |
ChoiceFormat.nextDouble, previousDouble | adjacent double values |
ListFormat.getInstance([Locale, Type, Style]) (22) | locale-specific list joining |
ListFormat.format(List), parse(String) | format and parse lists |
Summary
- Put whole sentences, not fragments, in
MessageFormatpatterns, so translators can reorder{0},{1}, ... - Use
{n,number,...},{n,date,...}, and since Java 23{n,dtf_date,...},{n,list}andcompact_short/compact_longstyles;date/timeonly acceptjava.util.Date. {0}formats numbers with grouping; use{0,number,#}for years and IDs.- In patterns,
'quotes text and''is an apostrophe;’needs no escaping. - For a non-default locale, create a
MessageFormatinstance and pass anObject[]. ChoiceFormatselects text by numeric intervals (#/≤inclusive,<exclusive). It handles English singular and plural but not the plural rules of languages such as Russian or Arabic; use ICU4J or restructure the message for those.ListFormat(Java 22) joins lists with the right separators and conjunctions.
Practice Questions
1. A translator writes "Impossible d'ouvrir {0}" and users see "Impossible douvrir {0}". What happened?
The pattern goes through MessageFormat, where a single apostrophe starts a quoted section. Everything after d' up to the end is treated as literal text, so the apostrophe disappears and {0} is not substituted. The translator must write d''ouvrir, or use the typographic apostrophe d’ouvrir.
2. Why does MessageFormat.format("Copyright {0}", 2025) print "Copyright 2,025", and how do you fix it?
Numbers in a plain placeholder are formatted with the default NumberFormat, which groups thousands. Use {0,number,#} (or {0,number,0}) for a number without grouping, or pass String.valueOf(2025).
3. Write a choice pattern that prints "no messages", "one message", or "N messages", and explain why the third choice contains a placeholder.
{0,choice,0#no messages|1#one message|1<{0,number,integer} messages}. Values ≤ 0 (and anything below 0) give the first text, exactly 1 the second, and anything greater than 1 the third. The chosen text is formatted again by the enclosing MessageFormat, so {0,number,integer} inside it is replaced by the actual count.
4. A program formats "{0,date,long}" with a LocalDate and gets an exception. What are the options?
The date type creates a java.text.DateFormat, which only formats java.util.Date and Number. On Java 23 and later, use {0,dtf_date,long}, which creates a DateTimeFormatter. On older versions, call setFormatByArgumentIndex(0, DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(locale).toFormat()), or format the date yourself and pass the string.
5. Why can't a ChoiceFormat produce correct Russian or Polish plurals, and what can you use instead?
A choice format maps numeric intervals to texts, but the plural categories of these languages depend on the last digits of the number (21 uses the same form as 1, but 11 does not), which no set of intervals can describe. Use a library that implements CLDR plural rules, such as ICU4J's MessageFormat with plural arguments, or phrase the message so the noun form does not depend on the number.
Previous: Localized Dates, Collation and Unicode Normalization in Java
Next: Text Boundaries, Line Endings, Console and Encodings in Java
Related reading
- Localized Dates, Collation and Unicode Normalization in Java
- Number Formats in Java: NumberFormat, Compact Numbers, DecimalFormat and Currencies
- Locales in Java: Language Tags, Default Locales and Display Names
- Formatting and Parsing Dates in Java, and Converting Legacy Date and Calendar
- LocalTime, ZonedDateTime and Daylight Saving Time in Java

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.