Quiz: MessageFormat in Java: Locale-Sensitive Messages with Parameters

Total: 7 questions

1. 

What is MessageFormat in Java, and why is it better than concatenation and String.format for localized messages?

java.text.MessageFormat builds a message from a pattern with numbered arguments {0}, {1}, {2} and formats the numbers and dates you pass in according to the rules of a locale:

MessageFormat.format("Hello, {0}! You have {1} new messages", "Anna", 3);
// Hello, Anna! You have 3 new messages

The number says which argument to insert, not where it stands, so a translator can reorder the words: "{0} uploaded {1} files" in English and "{1} Dateien hochgeladen von {0}" in German work with the same code. The whole pattern lives in a properties file next to the translation.

  • Concatenation hard-codes the word order in Java: translating the sentence means changing code.
  • String.format can reference an argument by index (%2$s), but few translators know that syntax, and it has no currency and no choosing text by a number.
  • MessageFormat offers {0,number,currency}, {0,number,percent}, {0,date,long} and {0,choice,…}.

For logs and strings nobody translates, String.format or plain concatenation is enough.

2. 

How is a {index,type,style} format element in a MessageFormat pattern structured?

An element is written in curly braces in one of three forms: {index}, {index,type} or {index,type,style}.

  • index is the zero-based argument number. The same number may appear in the pattern several times.
  • type is number, date, time or choice (Java 23 added dtf_date, list and others).
  • style is a predefined style (integer, currency, percent; short, medium, long, full) or your own pattern: {0,number,#,##0.00}, {0,date,yyyy-MM-dd}.

An untyped element formats a Number through the locale's NumberFormat (2026 becomes "2,026" in en_US), a Date in SHORT style, inserts a string as is, and null as "null". For years and IDs use {0,number,#}.

Extra arguments are ignored, and an element with no argument is printed as is: MessageFormat.format("{1} {0} {5}", "a", "b") gives b a {5}. A mistake in the pattern itself, such as an unknown type {0,foo}, an unclosed brace {0 or a name instead of a number {name}, throws IllegalArgumentException when the object is created. The JDK has no named parameters; ICU4J does.

3. 

Why does an apostrophe in a MessageFormat pattern break substitution, and how do you print a quote or a curly brace?

The single quote ' is a special character in a MessageFormat pattern: text between two quotes is printed literally, without parsing format elements. The pattern "Don't miss {0}" with the argument "x" prints Dont miss {0}: the quote opened a literal section, no closing quote followed, and {0} was never substituted. No exception is thrown.

  • Double the apostrophe: Don''t miss {0} → Don't miss x.
  • Quote a curly brace: '{'{0}'}' with the argument name → {name}.
  • The typographic apostrophe ’ (U+2019) and double quotes, straight or curly, are not special and need no escaping.

Doubling is needed only in strings that go through MessageFormat: a string shown straight from rb.getString() prints Don''t with two quotes. That is why teams agree to format every bundle string through MessageFormat, even when it has no parameters.

4. 

How does MessageFormat.format() differ from new MessageFormat(pattern, locale), and which locale should you pass when working with a ResourceBundle?

The static MessageFormat.format(pattern, args...) formats with the default locale (Locale.getDefault(Locale.Category.FORMAT)) and parses the pattern again on every call. The same line of code prints 1,234,567.891 on a machine with en_US and 1.234.567,891 with de_DE. The constructor new MessageFormat(pattern, locale) takes the locale explicitly, which is how server code is written: the locale comes from the request or the user profile, not from the JVM settings.

The object has no varargs method: arguments go in as an array, mf.format(new Object[]{"Anna"}). Calling mf.format("Anna") throws ClassCastException.

With a ResourceBundle, get the pattern with rb.getString(key) and format it with the locale the user asked for:

ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
return new MessageFormat(rb.getString(key), locale).format(args);

Not rb.getLocale(): for the file messages_de.properties it returns the locale de with no country, and {n,number,currency} prints the generic sign ¤ instead of the euro. Each properties file has its own argument order, and the code does not depend on it.

5. 

How does the choice type work in MessageFormat, and why can't it handle plurals in Russian or Polish?

The choice type (ChoiceFormat) picks a text variant by a numeric range. Each variant is a "limit#text" pair and applies from its limit up to the next one; 5# means "from 5 inclusive", 1< means "greater than 1". If the chosen text contains {0}, it is formatted once more:

"{0,choice,0#no files|1#one file|1<{0,number,integer} files}"
// 0 → no files, 1 → one file, 2 → 2 files, 1000 → 1,000 files

For English (zero, one, many) ranges are enough. In Russian, Polish and other Slavic languages the form depends on the last digits of the number, not on a range: the pattern 0#нет файлов|1#{0} файл|2#{0} файла|5#{0} файлов prints "21 файлов", "22 файлов", "101 файлов" (correct: "21 файл", "22 файла", "101 файл").

The JDK has no public class with CLDR plural rules, no equivalent of PluralRules. The options:

  • your own method that picks the one/few/many category from the remainders of division by 10 and by 100, with a separate properties string per form (files.one, files.few, files.many);
  • the ICU4J library: its com.ibm.icu.text.MessageFormat understands a plural type right in the pattern, {0, plural, one{# file} other{# files}}.
6. 

How does MessageFormat handle dates: Date, LocalDate and the new Java 23 types?

The date and time types work only with java.util.Date and a number of milliseconds. With them you can use a predefined style ({0,date,long} → "December 1, 2026" for en_US) or a SimpleDateFormat pattern ({0,date,yyyy-MM-dd} {0,time,HH:mm} → 2026-12-01 14:05).

A LocalDate, LocalDateTime or ZonedDateTime in a {0,date,long} element throws IllegalArgumentException: Cannot format given Object as a Date, on Java 21 and still on Java 25. Up to and including Java 22, format the date beforehand with DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(locale) and pass a string into the pattern; the downside is that the code, not the translator, now picks the date style.

Java 23 added new element types:

  • {0,dtf_date,long}, dtf_time, dtf_datetime for java.time;
  • names of predefined formatters, for example {0,ISO_LOCAL_DATE} → 2026-12-01;
  • {0,number,compact_short} → 1M for 1,200,000 in en_US;
  • {0,list} → a, b, and c, {0,list,or}.

On Java 21 and 22 such patterns throw IllegalArgumentException: unknown format type, so add them to bundles only after moving to Java 23 or 25.

7. 

Is MessageFormat thread-safe, and how do you use it in multithreaded code?

No. The Javadoc says so directly: "Message formats are not synchronized", and recommends a separate instance per thread. The object holds nested NumberFormat and DateFormat instances, which are not thread-safe either. One MessageFormat in a static field used by web server threads produces bugs that do not reproduce in tests: mixed-up digits in amounts, occasionally exceptions from deep inside DecimalFormat.

Safe options:

  • create the object on the spot, in the method that formats the message;
  • the static MessageFormat.format(): it creates a new object on every call, but also parses the pattern every time;
  • a ThreadLocal cache, if a profiler shows that pattern parsing matters: ThreadLocal.withInitial(() -> new MessageFormat(pattern, locale));
  • synchronized around format(): correct, but under load threads wait for each other.

A ThreadLocal pays off for long-lived pool threads. A virtual thread (Java 21) usually handles one task and ends, so the cache is filled again for every request; there, create the object on the spot.

Page 1 of 1