MessageFormat in Java: Locale-Sensitive Messages with Parameters
MessageFormat (java.text.MessageFormat) builds a finished 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. Arguments refer to a number, not to a position in the text, so a translator can reorder the words in the pattern without touching the code:
String s = MessageFormat.format("Hello, {0}! You have {1} new messages", "Anna", 3);
// Output: Hello, Anna! You have 3 new messages MessageFormat has rules of its own, and the very first English string can break them. The pattern "Don't miss {0}" with the argument "x" prints Dont miss {0}: the apostrophe is gone and the parameter was never substituted. No exception is thrown. The reason is explained in the section Single quotes and curly braces.
This lesson continues the module on internationalization and localization: the Locale class names the language and region, translations live in a ResourceBundle, and MessageFormat joins the translated text with your data.
Why MessageFormat when you have concatenation and String.format
MessageFormat is for messages that get translated into other languages. Concatenation hard-codes the word order in Java, while MessageFormat keeps the whole sentence in one pattern with numbered arguments: the pattern can move to a properties file, and the translator places {0} and {1} wherever their language needs them.
Take the message "a user uploaded N files". With concatenation it looks like this:
String msg = name + " uploaded " + count + " files"; German puts the verb at the end (Anna hat 3 Dateien hochgeladen), Japanese has its own order again. A string glued together in code leaves the translator nothing to change: translating the sentence means rewriting Java. With patterns, each language has its own string and the code stays the same:
// en: "{0} uploaded {1} files"
// de: "{1} Dateien hochgeladen von {0}"
String msg = MessageFormat.format(pattern, name, count); In the German pattern {1} comes before {0}, and that's fine: the number says which argument to insert, not where it stands in the sentence.
| Feature | Concatenation + | String.format | MessageFormat |
|---|---|---|---|
| How an argument is referenced | It isn't: the order is fixed by the code | By order %s or by index %2$s | Only by number {1} |
| Reordering words in a translation | Impossible without changing code | Possible with %2$s, but few translators know that syntax | Standard practice |
| Locale awareness | None: toString() on numbers always uses a dot | String.format(locale, …), otherwise the default locale | new MessageFormat(p, locale), otherwise the default locale |
| Currency, percentages, dates | By hand | Numbers and dates (%,.2f, %tB), no currency | {0,number,currency}, {0,number,percent}, {0,date,long} |
| Choosing text by a number | An if in the code | No | {0,choice,…} |
| Escaping | Not needed | %% for a percent sign | '' for an apostrophe, '{' for a brace |
| Where the pattern lives | Only in code | In code or in properties | In properties, next to the translation |
For logs, debug output and strings nobody translates, String.format or plain concatenation is enough. The %s, %d and %f specifiers are covered in the lesson Java String.format().
Pattern syntax: {index,type,style}
A format element in a MessageFormat pattern is written in curly braces in one of three forms: {index}, {index,type} or {index,type,style}. Here index is the zero-based argument number, type is number, date, time or choice, and style is a predefined style or your own format pattern.
| Element | What it does | Example for en_US |
|---|---|---|
{0} | No type: a Number goes through the locale's NumberFormat, a Date becomes date and time in SHORT style, a String is inserted as is, anything else via toString(), null becomes the string "null" | 2026 → 2,026 |
{0,number} | A number by the locale's rules | 1234.5 → 1,234.5 |
{0,number,integer} | An integer; the fraction is rounded (HALF_EVEN) | 7.6 → 8 |
{0,number,currency} | An amount in the currency of the locale's country | 1234.5 → $1,234.50 |
{0,number,percent} | A percentage; the number is multiplied by 100 | 0.25 → 25% |
{0,number,#,##0.00} | Your own DecimalFormat pattern; separator characters come from the locale | 1234.5 → 1,234.50 |
{0,date,short|medium|long|full} | A date in one of the locale's predefined styles | long: December 1, 2026 |
{0,date,yyyy-MM-dd} | A date by a SimpleDateFormat pattern | 2026-12-01 |
{0,time,short|medium|long|full} | A time in the locale's style (also accepts a pattern, like date) | short: 2:05 PM (on JDK 20+ the space before PM is U+202F) |
{0,choice,0#…|1#…} | Picks text by a numeric range (ChoiceFormat) | see ChoiceFormat and plurals |
Several number styles in one pattern:
import java.text.MessageFormat;
import java.util.Locale;
public class SyntaxExample {
public static void main(String[] args) {
MessageFormat mf = new MessageFormat(
"Year {0}, total {1,number,currency}, share {2,number,percent}, {3,number,integer}",
Locale.US);
System.out.println(mf.format(new Object[]{2026, 1234.5, 0.25, 7.6}));
}
}
// Output: Year 2,026, total $1,234.50, share 25%, 8 You can pass more or fewer arguments than the pattern has elements. Extra arguments are ignored, and an element with no matching argument is printed as is, braces included:
// Default locale en_US
System.out.println(MessageFormat.format("{1} {0} {5}", "a", "b")); // Output: b a {5}
System.out.println(MessageFormat.format("{0} {1}", null, "x")); // Output: null x A mistake in the pattern itself is different: it throws an exception when the object is created, before format() is ever called. The static MessageFormat.format() creates and formats in a single call, so there the exception comes out of that call.
new MessageFormat("{0,foo}");
// java.lang.IllegalArgumentException: unknown format type: foo
new MessageFormat("{0");
// java.lang.IllegalArgumentException: Unmatched braces in the pattern. MessageFormat.format() vs new MessageFormat(pattern, locale)
The static method MessageFormat.format(pattern, args...) formats with the default locale (Locale.getDefault(Locale.Category.FORMAT)) and parses the pattern again on every call. The constructor new MessageFormat(pattern, locale) takes the locale explicitly, which is how you write web and server code, where the user's language has nothing to do with the JVM settings.
The same line of code gives different results on different machines:
Locale.setDefault(Locale.Category.FORMAT, Locale.US);
System.out.println(MessageFormat.format("{0}", 1234567.891)); // Output: 1,234,567.891
Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY);
System.out.println(MessageFormat.format("{0}", 1234567.891)); // Output: 1.234.567,891 On a server the default locale comes from the operating system or the JVM launch options, while the users are many and speak different languages. So server code takes the locale from the request or the user profile and passes it to the constructor. How locale categories and Locale.setDefault work is covered in The default locale: getDefault and setDefault.
One pattern in three locales. The date is created with GregorianCalendar in the default time zone and formatted in the same zone, so the day doesn't shift:
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
public class MessageFormatLocales {
public static void main(String[] args) {
String pattern = "{0,date,long} | {1,number,currency} | {2,number,percent}";
Date date = new GregorianCalendar(2026, Calendar.DECEMBER, 1).getTime();
Locale[] locales = {Locale.US, Locale.GERMANY, Locale.FRANCE};
for (Locale locale : locales) {
MessageFormat mf = new MessageFormat(pattern, locale);
System.out.println(locale + ": " + mf.format(new Object[]{date, 1234.5, 0.25}));
}
}
} en_US: December 1, 2026 | $1,234.50 | 25%
de_DE: 1. Dezember 2026 | 1.234,50 € | 25 %
fr_FR: 1 décembre 2026 | 1 234,50 € | 25 % Note the call mf.format(new Object[]{…}). A MessageFormat object has no varargs method like the static format: the arguments go in as a single array.
Spaces that aren't spaces
The spaces before € and % in the German and French lines, and the group separator in 1 234,50, are non-breaking characters inserted by the locale's NumberFormat. An assertEquals against a string typed with ordinary spaces fails. The details and a workaround are in the lesson Java NumberFormat.
Numbers in a pattern: grouping separators and rounding
A number in an untyped {0} element is formatted as a regular locale number, which means with a grouping separator: 2026 becomes "2,026" in en_US and "2 026" in ru_RU. For years, order numbers and IDs, use {0,number,#} or pass a string.
import java.text.MessageFormat;
import java.util.Locale;
public class NumbersExample {
public static void main(String[] args) {
Locale us = Locale.US;
System.out.println(new MessageFormat("Report for {0}", us)
.format(new Object[]{2026}));
System.out.println(new MessageFormat("Report for {0,number,#}", us)
.format(new Object[]{2026}));
System.out.println(new MessageFormat("Report for {0}", us)
.format(new Object[]{String.valueOf(2026)}));
System.out.println(new MessageFormat("{0,number,integer} pcs", us)
.format(new Object[]{7.6}));
}
}
// Output:
// Report for 2,026
// Report for 2026
// Report for 2026
// 8 pcs The year bug slips through development easily: tests use numbers like 5 or 42, and "Order #1,048,576" shows up only in production. The integer style doesn't truncate the fraction, it rounds it with HALF_EVEN, just like NumberFormat: 7.6 gives 8. The rounding rule is explained in Rounding in NumberFormat.
Single quotes and curly braces
In a MessageFormat pattern the single quote ' is a special character: text between two quotes is printed literally, without parsing format elements. To print an apostrophe, double it: ''. To print a curly brace, quote it: '{'.
import java.text.MessageFormat;
import java.util.Locale;
public class QuotesExample {
public static void main(String[] args) {
Locale us = Locale.US;
System.out.println(new MessageFormat("Don't miss {0}", us).format(new Object[]{"x"}));
System.out.println(new MessageFormat("Don''t miss {0} '{1}'", us).format(new Object[]{"x"}));
System.out.println(new MessageFormat("File ''{0}'' saved", us).format(new Object[]{"report.txt"}));
System.out.println(new MessageFormat("File “{0}” saved", us).format(new Object[]{"report.txt"}));
System.out.println(new MessageFormat("Template: '{'{0}'}'", us).format(new Object[]{"name"}));
}
}
// Output:
// Dont miss {0}
// Don't miss x {1}
// File 'report.txt' saved
// File “report.txt” saved
// Template: {name} The first line is the case from the start of the lesson. The quote in Don't opened a literal section, no closing quote followed, and everything up to the end of the pattern, {0} included, was printed as is. The quote itself disappeared. In the second line '' turned into an apostrophe, and '{1}' became the text {1} with no substitution.
English text is full of apostrophes (don't, it's, Anna's), so this bites English bundles more than most. Two ways around it: double every apostrophe, or use the typographic apostrophe ’ (U+2019). It isn't a special character, so Don’t miss {0} formats correctly and prints Don’t miss x. Double quotes, straight or curly, need no escaping at all.
One rule for the whole bundle
Doubling the quote is needed only in strings that go through MessageFormat. If a string without parameters is shown straight from rb.getString(), the user sees Don''t with two quotes. To spare translators the guesswork, agree as a team that every string from the bundle is formatted through MessageFormat, even when it has no parameters.
MessageFormat with ResourceBundle: patterns in properties files
MessageFormat patterns usually live in ResourceBundle properties files: the code gets the string with rb.getString(key) and formats it with new MessageFormat(pattern, locale) using the same locale the bundle was loaded for. Each file has its own argument order, and the code doesn't depend on it.
Two files in src/main/resources:
# messages_en.properties
cart.summary = {0}''s cart contains {1,number,integer} items
# messages_de.properties
cart.summary = Im Warenkorb: {1,number,integer} Artikel (Kunde {0}) import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class BundleMessages {
static String message(String key, Locale locale, Object... args) {
ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
return new MessageFormat(rb.getString(key), locale).format(args);
}
public static void main(String[] args) {
System.out.println(message("cart.summary", Locale.US, "Anna", 3));
System.out.println(message("cart.summary", Locale.GERMANY, "Anna", 3));
}
}
// Output:
// Anna's cart contains 3 items
// Im Warenkorb: 3 Artikel (Kunde Anna) In the English file the apostrophe is written as '', following the rule from the previous section. MessageFormat receives the requested locale, not rb.getLocale(), and that matters. For the file messages_de.properties, rb.getLocale() returns the locale de with no country, and a {n,number,currency} element would print the generic currency sign ¤ instead of the euro (the reason is in the currency section of the NumberFormat lesson).
How getBundle() finds files, what happens when a key is missing, and which encoding to use for non-ASCII text is covered in the ResourceBundle lesson.
ChoiceFormat and plurals
The choice type picks a text variant by a number: {0,choice,0#no files|1#one file|1<{0,number,integer} files}. Each variant is a "limit#text" pair and applies from its limit up to the next one. For English (zero, one, many) that's enough. For Russian, Polish and other Slavic languages it isn't: the form depends on the last digits of the number, not on a range.
5#… means "from 5 inclusive", 1<… means "greater than 1". If the chosen text contains {0}, MessageFormat formats it once more, which is how the number ends up inside the variant. The English version:
MessageFormat en = new MessageFormat(
"{0,choice,0#no files|1#one file|1<{0,number,integer} files}", Locale.US);
for (int n : new int[]{0, 1, 2, 1000}) {
System.out.println(en.format(new Object[]{n}));
}
// Output:
// no files
// one file
// 2 files
// 1,000 files The intro example of this lesson needs the same fix: with 1 instead of 3 it prints Hello, Anna! You have 1 new messages.
Now hand the pattern to a Russian translator. Russian has three integer forms: "файл" (1, 21, 101), "файла" (2–4, 22–24) and "файлов" (5–20, 25–30). A range-based pattern looks reasonable and breaks above 20:
MessageFormat ru = new MessageFormat(
"{0,choice,0#нет файлов|1#{0} файл|2#{0} файла|5#{0} файлов}", Locale.of("ru", "RU"));
for (int n : new int[]{0, 1, 2, 5, 21, 22, 101}) {
System.out.println(ru.format(new Object[]{n}));
}
// Output:
// нет файлов
// 1 файл
// 2 файла
// 5 файлов
// 21 файлов
// 22 файлов
// 101 файлов 21, 22 and 101 fell into the "from 5" range, although the correct forms are "21 файл", "22 файла" and "101 файл". The Russian rule (per CLDR) is based on the remainder of division by 10 and by 100, and Polish works the same way. The JDK has no public class with these rules, no equivalent of ICU's PluralRules, so you pick the key yourself and keep one properties string per form:
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;
public class RussianPlural {
// CLDR categories for Russian integers: one, few, many
static String pluralCategory(long n) {
long abs = Math.abs(n);
long mod10 = abs % 10;
long mod100 = abs % 100;
if (mod10 == 1 && mod100 != 11) return "one";
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return "few";
return "many";
}
public static void main(String[] args) {
// The same keys would sit in messages_ru.properties
Map<String, String> bundle = Map.of(
"files.one", "{0} файл",
"files.few", "{0} файла",
"files.many", "{0} файлов");
Locale ru = Locale.of("ru", "RU");
for (long n : new long[]{0, 1, 2, 5, 11, 21, 22, 101, 112}) {
String pattern = bundle.get("files." + pluralCategory(n));
System.out.print(new MessageFormat(pattern, ru).format(new Object[]{n}) + "; ");
}
}
}
// Output: 0 файлов; 1 файл; 2 файла; 5 файлов; 11 файлов; 21 файл; 22 файла; 101 файл; 112 файлов; The method is written for integers. Fractions ("1.5 files") have a separate CLDR category, other. An English bundle in this scheme needs only files.one and files.many, so the category method is written per language.
When you support many languages, take the rules from the ICU4J library. Its com.ibm.icu.text.MessageFormat understands a plural type with CLDR categories right in the pattern: {0, plural, one{# file} other{# files}} for English, {0, plural, one{# файл} few{# файла} many{# файлов} other{# файла}} for Russian. The translator writes every form in one string, and the code knows nothing about grammar.
Dates: Date, LocalDate and IllegalArgumentException
The date and time types in a MessageFormat pattern work only with java.util.Date and with a number of milliseconds (Number). 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.
With a Date you can use a predefined style or a pattern. One argument may appear in the pattern several times:
Date date = new GregorianCalendar(2026, Calendar.DECEMBER, 1, 14, 5).getTime();
System.out.println(new MessageFormat("{0,date,yyyy-MM-dd} {0,time,HH:mm}", Locale.US)
.format(new Object[]{date}));
// Output: 2026-12-01 14:05 For java.time up to and including Java 22 there is one workaround: format the date beforehand with DateTimeFormatter and pass the finished string into the pattern.
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class DatesExample {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 12, 1);
Locale us = Locale.US;
try {
new MessageFormat("Delivery on {0,date,long}", us).format(new Object[]{date});
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
String formatted = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.withLocale(us)
.format(date);
System.out.println(new MessageFormat("Delivery on {0}", us).format(new Object[]{formatted}));
}
}
// Output:
// Cannot format given Object as a Date
// Delivery on December 1, 2026 The downside is that the date style is now chosen by the code, not by the translator in the pattern. Another option is converting to Date (Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant())), but then the time zone gets involved. DateTimeFormatter styles and patterns are covered in the lesson DateTimeFormatter in Java.
New format types in Java 23: dtf_date, list, compact_short
In Java 23 MessageFormat learned to handle java.time and got new element types: dtf_date, dtf_time, dtf_datetime, the names of predefined DateTimeFormatter constants (such as ISO_LOCAL_DATE), compact numbers compact_short / compact_long, and lists with list. On Java 21 and 22 such a pattern throws IllegalArgumentException: unknown format type.
| Element | Since | Example | Output |
|---|---|---|---|
{0,dtf_date,long} | Java 23 | LocalDate.of(2026, 12, 1), en_US | December 1, 2026 |
{0,dtf_time,…}, {0,dtf_datetime,…} | Java 23 | Styles short, medium, long, full | Time and date-time by the locale's rules |
{0,ISO_LOCAL_DATE} | Java 23 | LocalDate.of(2026, 12, 1) | 2026-12-01 |
{0,number,compact_short} | Java 23 | 1_200_000, en_US | 1M |
{0,number,compact_long} | Java 23 | 1_200_000, en_US | 1 million |
{0,list} | Java 23 (the ListFormat class: Java 22) | List.of("a", "b", "c"), en_US | a, b, and c |
{0,list,or} | Java 23 | List.of("a", "b", "c"), en_US | a, b, or c |
// Java 23+
import java.text.MessageFormat;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;
public class Java23Formats {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 12, 1);
Locale us = Locale.US;
List<String> items = List.of("a", "b", "c");
System.out.println(new MessageFormat("{0,dtf_date,long}", us).format(new Object[]{date}));
System.out.println(new MessageFormat("{0,ISO_LOCAL_DATE}", us).format(new Object[]{date}));
System.out.println(new MessageFormat("{0,number,compact_short}", us)
.format(new Object[]{1_200_000}));
System.out.println(new MessageFormat("{0,number,compact_long}", us)
.format(new Object[]{1_200_000}));
System.out.println(new MessageFormat("{0,list}", us).format(new Object[]{items}));
System.out.println(new MessageFormat("{0,list,or}", us).format(new Object[]{items}));
}
}
// Output (Java 23+):
// December 1, 2026
// 2026-12-01
// 1M
// 1 million
// a, b, and c
// a, b, or c
// Java 21 and 22:
// java.lang.IllegalArgumentException: unknown format type: dtf_date If the project is still on Java 21 LTS and someone writes properties patterns "for the future", the first dtf_date in a file breaks loading of that message. Add the new types to bundles only after moving to Java 23 or 25.
Is MessageFormat thread-safe?
No, MessageFormat is not thread-safe. The Javadoc says so directly: "Message formats are not synchronized", and recommends a separate instance per thread. Internally the object holds nested NumberFormat and DateFormat instances, which aren't thread-safe either.
An instance in a static field used concurrently by web server threads produces bugs that don't reproduce in tests: mixed-up digits in amounts, occasionally exceptions from deep inside DecimalFormat. There are three safe options. The simplest is creating the object on the spot, as the message() method in the ResourceBundle section does. The static MessageFormat.format() is safe as well, since it creates a new object on every call, but it also parses the pattern every time. If a profiler shows that pattern parsing matters, cache the object in a ThreadLocal:
private static final ThreadLocal<MessageFormat> GREETING = ThreadLocal.withInitial(
() -> new MessageFormat("Hello, {0}!", Locale.US));
String text = GREETING.get().format(new Object[]{"Anna"}); // Hello, Anna! The third option is synchronized around the format() call. It's correct, but under load the threads start waiting for each other.
ThreadLocal and virtual threads
A ThreadLocal cache pays off when threads live long, as in a pool. A virtual thread (Java 21) usually handles one task and ends, so the ThreadLocal is filled again for every request and saves nothing. In such code, create the MessageFormat on the spot.
Other methods: parse, applyPattern, setLocale
Besides format(), MessageFormat has methods to replace the pattern (applyPattern), get it back as a string (toPattern), swap the formatter for a single argument, and parse a finished string back into an array of arguments (parse). setLocale affects only patterns applied after the call.
| Method | What it does | Non-obvious detail |
|---|---|---|
applyPattern(String) | Replaces the pattern of an existing object | A bad pattern throws IllegalArgumentException, as in the constructor |
toPattern() | Returns the current pattern as a string | May differ from the original: the pattern is rebuilt from the nested formatters |
setFormatByArgumentIndex(int, Format) | Sets your own Format for the argument with that number | Applies to every element with that number in the pattern |
getFormatsByArgumentIndex() | Returns the formatters indexed by argument number | An element without a type has null in the array |
parse(String) | Parses a string by the pattern and returns Object[] | Checked ParseException if the string doesn't match; numbers come back as Long or Double |
getLocale(), setLocale(Locale) | The locale used to create nested formatters | setLocale doesn't change an already parsed pattern: call applyPattern again |
Parsing a string back by the pattern:
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Locale;
public class ParseExample {
public static void main(String[] args) throws ParseException {
MessageFormat mf = new MessageFormat("{0} bought {1,number,integer} pcs.", Locale.US);
Object[] values = mf.parse("Anna bought 3 pcs.");
System.out.println(Arrays.toString(values));
System.out.println(values[1].getClass().getName());
}
}
// Output:
// [Anna, 3]
// java.lang.Long The number came back as a Long, not an Integer, even if you passed an int when formatting. The cast (Integer) values[1] throws ClassCastException, so read it with ((Number) values[1]).intValue().
The call order when changing the locale:
MessageFormat mf = new MessageFormat("{0,number}", Locale.US);
mf.setLocale(Locale.GERMANY);
System.out.println(mf.format(new Object[]{1234.5})); // Output: 1,234.5 (the formatter is still American)
mf.applyPattern(mf.toPattern());
System.out.println(mf.format(new Object[]{1234.5})); // Output: 1.234,5 Where MessageFormat code goes wrong
Most MessageFormat mistakes throw no exception: the message is simply printed wrong, and users notice it before the tests do. The table lists the cases that come up most often, how to recognize each one, and the fix.
| Mistake | What happens | How to fix it |
|---|---|---|
An apostrophe in the pattern: Don't miss {0} | Dont miss {0}: the quote vanished, parameters after it aren't substituted | Don''t or the typographic ’ |
A year or order number in {0} | 2,026, 1,048,576: a grouping separator | {0,number,#} or pass a String |
LocalDate in {0,date,long} | IllegalArgumentException: Cannot format given Object as a Date | Up to Java 22: DateTimeFormatter and a string; Java 23+: {0,dtf_date,long} |
Static MessageFormat.format() on a server | Numbers and dates in the JVM's locale, not the user's | new MessageFormat(pattern, userLocale) |
choice for Russian or Polish plurals | 21 файлов, 22 файлов, 101 файлов | Pick the one/few/many key in code, or ICU4J plural |
One MessageFormat in a static field shared by all threads | Occasionally scrambled digits or exceptions under load | A new object per call, ThreadLocal or synchronized |
A sentence built from several keys: rb.getString("found") + n + rb.getString("files") | The translator can't change the word order | The whole sentence is one key with {0} |
mf.format("Anna"): a single string instead of an array | ClassCastException: the instance format() expects Object[] | mf.format(new Object[]{"Anna"}) |
The formatting locale is taken from rb.getLocale() | The messages_de file has a locale without a country, so currency prints as ¤ | Pass the locale the user asked for |
Frequently Asked Questions
Can MessageFormat use named parameters like {name}?
No, the JDK supports only numbers: new MessageFormat("{name}") throws IllegalArgumentException: can't parse argument number: name. Named arguments with a Map are available in ICU4J's com.ibm.icu.text.MessageFormat. For plain substitution without locale formatting, StringSubstitutor from Apache Commons Text with ${name} placeholders works.
MessageFormat or String.format: which one for UI messages?
If the string will be translated, use MessageFormat: the numbered pattern lives in properties, the translator can reorder words, and currency and dates follow the locale. String.format is handier for logs and technical strings. A point-by-point comparison is in the table in Why MessageFormat.
Does the JDK have plural rules like ICU's PluralRules?
There is no public class with CLDR plural rules in the JDK. ChoiceFormat picks text only by numeric ranges, which is fine for English and gives "21 файлов" in Russian. The options are your own one/few/many method per language or the ICU4J library. The method and an example with output are in ChoiceFormat and plurals.
Will String Templates (STR."…") replace MessageFormat?
No. String Templates were a preview feature in Java 21 (JEP 430) and Java 22 (JEP 459) and were removed in JDK 23. Besides, the template was written in Java code, while a translation has to live in a properties file, so they were never meant for localization. For localized messages the JDK still relies on MessageFormat.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
All module tasks →
Comments