MessageFormat
Build grammatically correct plural messages in Java with MessageFormat and choice patterns, with example outputs.
2 min readUpdated
java.text.MessageFormat builds a message from a pattern with numbered placeholders such as {0}. A placeholder can carry a choice format, which picks a piece of text based on a number. That solves the classic “1 arguments” problem: the message reads correctly for zero, one and many without any if statements in the code.
Pluralise a message
This program reports how many command-line arguments it received:
import java.text.MessageFormat;import java.util.logging.Logger;import static java.util.logging.Level.INFO;
public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) { String pattern = "You passed{0,choice,0# no |1# one |1< {0} }argument{0,choice,0#|1<s}"; String message = MessageFormat.format(pattern, args.length); logger.log(INFO, message); }}MessageFormat.format fills placeholder {0} with args.length in both places it appears.
Read the choice patterns
A choice format is a list of limit#text pairs separated by |. MessageFormat picks the last pair whose limit the number meets. # means “greater than or equal to”, and < means “strictly greater than”.
The first placeholder, {0,choice,0# no |1# one |1< {0} }, chooses the word for the count:
0# no: if the value is 0, printno.1# one: if the value is 1, printone.1< {0}: if the value is greater than 1, print the number itself (2, 3, and so on). A placeholder inside the chosen text is formatted again.
The spaces around each word are part of the text. They separate it from “passed” and “argument”, which have no spaces of their own in the pattern.
The second placeholder, argument{0,choice,0#|1<s}, adds the plural ending:
0#: from 0 upwards, add nothing.1<s: above 1, adds.
1 falls under 0#, because 1 is not greater than 1, so it also gets no ending.
Example outputs
args.length |
Output |
|---|---|
| 0 | You passed no argument |
| 1 | You passed one argument |
| 2 | You passed 2 arguments |
| 5 | You passed 5 arguments |
Note: choice formats work for English, where only “one” and “other” differ. Languages with more plural forms, such as Polish or Arabic, need a plural-rule-aware formatter, for example ICU’s MessageFormat with plural arguments.