Java Resource Bundles: Properties Files, Lookup Order, MessageFormat and Properties (OCP 21)
Resource bundles for the OCP 21 exam: properties file naming, getBundle with and without a locale, the search order through requested locale, default locale and base bundle, key inheritance, MissingResourceException, MessageFormat placeholders and the Properties class.
kvi5hnuCode Sprout team member7 min readOn this page
Localized formatting covers numbers and dates. The words of an application, such as labels, greetings and error messages, also need translating. Hard-coding them in Java means recompiling for every language. A resource bundle keeps them outside the code: a set of key/value files, one per locale, from which Java picks the best match at runtime.
Properties files
A resource bundle is usually stored as .properties files. The file name is the bundle base name, then _ and the locale, then .properties:
# Gallery.properties (the base bundle: no locale)
name=City Gallery
exit=Exit
# Gallery_en.properties
welcome=Welcome to {0}, {1}!
hours=Open {0} to {1}
# Gallery_fr.properties
welcome=Bienvenue au {0}, {1} !
Format rules:
| Rule | Example |
|---|---|
A key and value can be separated by =, : or whitespace | theme = dark, maxVisitors:250, tagline Art for everyone |
# or ! starts a comment line | # gallery settings |
| Whitespace around the key and separator is ignored, but trailing whitespace in a value is kept | key = value␣␣ gives "value␣␣" |
A \ at the end of a line continues the value on the next line | long=first \ + second gives first second |
Escape spaces in keys and write Unicode with \uXXXX | key\ with\ space=v, cafe=caf\u00e9 (gives café) |
| The last duplicate key wins |
Since Java 9, properties resource bundles are read as UTF-8, falling back to ISO-8859-1 if the file isn't valid UTF-8. Before that you needed \u escapes for anything that wasn't Latin-1. For the exam you only need to read key=value lines. You can assume any file the exam shows exists on the class path.
Getting a bundle and reading values
ResourceBundle rb = ResourceBundle.getBundle("Gallery", Locale.CANADA); // a specific locale
ResourceBundle rb2 = ResourceBundle.getBundle("Gallery"); // the default locale
rb.getString("name"); // throws MissingResourceException if the key isn't found
rb.getObject("name"); // the same lookup, returning Object
rb.containsKey("gift"); // true or false
rb.keySet(); // every key, including inherited ones
rb.getLocale(); // the locale of the bundle that was actually chosen
MissingResourceException is unchecked, a RuntimeException. It's thrown both when no bundle can be found and when a key can't be found.
Step 1: which bundle?
For getBundle("Gallery", requested), Java tries file names from most specific to least specific, and the first one that exists is chosen:

| Step | Tries | Why |
|---|---|---|
| 1 | Gallery_fr_FR | requested language and country |
| 2 | Gallery_fr | requested language |
| 3 | Gallery_en_US | default locale's language and country |
| 4 | Gallery_en | default locale's language |
| 5 | Gallery | the base bundle |
| 6 | throw MissingResourceException | nothing available |
This assumes a requested locale of fr_FR and a default of en_US. Remember it as requested locale → default locale → base bundle, and for each locale, language_COUNTRY, then language. Steps without a country are skipped. Requesting Locale.of("en") with the default Locale.of("hi") tries only three files: _en, _hi, then the base bundle.
Java can also load bundles from classes (ListResourceBundle subclasses). At each step a class with the matching name is tried before the .properties file. The exam uses properties files.
Step 2: which file supplies each key?
Once a bundle has been chosen, its parents are the names you get by removing locale parts: Gallery_en_CA → Gallery_en → Gallery. getString looks in the chosen bundle and then up that chain only:
Locale.setDefault(Locale.US);
var rb = ResourceBundle.getBundle("Gallery", Locale.CANADA); // Gallery_en_CA exists: chosen
rb.getString("gift"); // Gallery_en_CA
rb.getString("welcome"); // not in en_CA, found in Gallery_en
rb.getString("name"); // not in en_CA or en, found in Gallery: "City Gallery"
name came from the base bundle, even though Gallery_en_US, the default locale's file, has a different name. The default locale matters only in step 1, when nothing for the requested locale exists. If Gallery_fr is chosen and a key exists only in Gallery_en, the result is a MissingResourceException, not English text.
MessageFormat
Bundle values often contain numbered placeholders. java.text.MessageFormat fills them in:
String pattern = rb.getString("welcome"); // Welcome to {0}, {1}!
MessageFormat.format(pattern, rb.getString("name"), "Priya"); // Welcome to City Gallery, Priya!
MessageFormat.format(String pattern, Object... arguments)is static and takes varargs.{0}is the first argument,{1}the second, and so on. A placeholder can be used more than once, in any order.- Missing arguments leave the placeholder as text (
Open 9:00 to {1}), and extra arguments are ignored. - Numbers and dates are formatted using the locale:
{0}with1234prints1,234in the US. You can add a style, as in{0,number,#.##}or{1,date,short}. - A single quote is MessageFormat's escape character.
"It's {0}"printsIts {0}: the quote disappears and everything after it is literal. Write''to get a quote:"It''s {0}"printsIt's free. This catches out many real translations. - An unclosed brace makes it throw
IllegalArgumentException.
The Properties class
java.util.Properties is a Hashtable<Object,Object> used as a map of String keys to String values, often loaded from a .properties file outside any bundle:
var props = new Properties();
props.setProperty("theme", "dark");
props.load(reader); // reads key=value lines (throws IOException)
props.getProperty("theme"); // "dark"
props.getProperty("cafe"); // null
props.getProperty("cafe", "closed"); // "closed": a default for a missing key
props.get("theme"); // "dark", but typed Object (from Hashtable)
props.get("cafe", "closed"); // DOES NOT COMPILE: get takes one argument
Only getProperty has the two-argument form with a default. get is the inherited single-argument Map method that returns Object. If a non-String value is put into a Properties, getProperty returns null for that key. Like any Hashtable, it rejects null keys and values with a NullPointerException. Properties.load(Reader) uses the reader's charset, but load(InputStream) still assumes ISO-8859-1; the UTF-8 default applies only to PropertyResourceBundle.
What's current
ResourceBundle,MessageFormatandPropertiesdidn't change in Java 22 through 25.- Since Java 9, properties bundles are read as UTF-8 (falling back to ISO-8859-1), so
\uescapes are no longer needed for non-Latin text. - The old COMPAT locale data was removed in Java 23. Locale-dependent output comes from CLDR data, which can change slightly between JDK versions (article 71).
Exam traps from this article
A complete example
A gallery app with a small set of bundles. To keep the program self-contained, the .properties text lives in a Map, and a ResourceBundle.Control reads it instead of the class path. Everything else, including the search order, parent chains and exceptions, is the JDK's real resource-bundle machinery. The program prints the search order for three locales, which bundle each request chose and where every key came from, the missing-key and missing-bundle errors, MessageFormat substitution (with the apostrophe trap), and Properties defaults.
import java.io.IOException;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.TreeSet;
public class Solution {
// The .properties "files" of this demo, kept in memory so the program is self-contained
static final Map<String, String> FILES = Map.of(
"Gallery.properties", "name=City Gallery\nexit=Exit\n",
"Gallery_en.properties", "welcome=Welcome to {0}, {1}!\nhours=Open {0} to {1}\n",
"Gallery_en_US.properties", "name=The Gallery\n",
"Gallery_en_CA.properties", "gift=Gift shop on level {0}\n",
"Gallery_fr.properties", "welcome=Bienvenue au {0}, {1} !\n",
"Menu_fr.properties", "soup=Soupe du jour\n");
// Loads bundles from FILES instead of the class path; the lookup rules are the JDK's own
static final ResourceBundle.Control IN_MEMORY = new ResourceBundle.Control() {
@Override
public List<String> getFormats(String baseName) {
return FORMAT_PROPERTIES;
}
@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format,
ClassLoader loader, boolean reload) throws IOException {
String text = FILES.get(toBundleName(baseName, locale) + ".properties");
return text == null ? null : new PropertyResourceBundle(new StringReader(text));
}
};
static ResourceBundle bundle(String base, Locale locale) {
ResourceBundle.clearCache();
return ResourceBundle.getBundle(base, locale, IN_MEMORY);
}
// The file names Java would try, in order: requested locale, then the default locale, then the base bundle
static List<String> searchOrder(String base, Locale requested) {
List<String> order = new ArrayList<>();
for (Locale l : List.of(requested, Locale.getDefault())) {
for (Locale c : IN_MEMORY.getCandidateLocales(base, l)) {
String file = IN_MEMORY.toBundleName(base, c) + ".properties";
if (!c.equals(Locale.ROOT) && !order.contains(file)) order.add(file);
}
}
order.add(base + ".properties");
return order;
}
static String get(ResourceBundle rb, String key) {
try {
return rb.getString(key);
} catch (MissingResourceException e) {
return "<MissingResourceException: " + e.getKey() + ">";
}
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
System.out.println("1) search order for Gallery (default locale en_US)");
for (Locale l : List.of(Locale.CANADA, Locale.FRANCE, Locale.of("ja"))) {
System.out.println(" " + l + ": " + String.join(" > ", searchOrder("Gallery", l)));
}
System.out.println("2) en_CA: the bundle chosen, then keys from its parents");
ResourceBundle ca = bundle("Gallery", Locale.CANADA);
System.out.println(" chosen bundle locale: " + ca.getLocale());
for (String key : new TreeSet<>(ca.keySet())) {
System.out.println(" " + key + " = " + ca.getString(key));
}
System.out.println("3) fr_FR: Gallery_fr wins, so en and en_US are never consulted");
ResourceBundle fr = bundle("Gallery", Locale.FRANCE);
System.out.println(" chosen bundle locale: " + fr.getLocale());
System.out.println(" name = " + get(fr, "name") + " (from Gallery.properties)");
System.out.println(" hours = " + get(fr, "hours") + " (only in Gallery_en)");
System.out.println("4) ja: no ja bundle, so the default locale's bundle is used");
ResourceBundle ja = bundle("Gallery", Locale.of("ja"));
System.out.println(" chosen bundle locale: " + ja.getLocale() + ", name = " + ja.getString("name"));
System.out.println("5) no bundle at all");
try {
bundle("Menu", Locale.ITALY);
} catch (MissingResourceException e) {
System.out.println(" Menu for it_IT -> MissingResourceException");
}
System.out.println("6) MessageFormat fills {0}, {1}, ...");
System.out.println(" " + MessageFormat.format(ca.getString("welcome"), ca.getString("name"), "Priya"));
System.out.println(" " + MessageFormat.format(fr.getString("welcome"), fr.getString("name"), "Priya"));
System.out.println(" " + MessageFormat.format(ca.getString("hours"), "9:00"));
System.out.println(" " + MessageFormat.format("It's {0}", "free") + " vs "
+ MessageFormat.format("It''s {0}", "free"));
System.out.println("7) Properties");
Properties settings = new Properties();
settings.load(new StringReader("""
# gallery settings
theme = dark
maxVisitors:250
tagline Art for everyone
"""));
System.out.println(" theme=" + settings.getProperty("theme")
+ ", maxVisitors=" + settings.getProperty("maxVisitors")
+ ", tagline=" + settings.getProperty("tagline"));
System.out.println(" missing: " + settings.getProperty("cafe")
+ ", with default: " + settings.getProperty("cafe", "closed")
+ ", get(): " + settings.get("theme"));
}
}
Output:
1) search order for Gallery (default locale en_US)
en_CA: Gallery_en_CA.properties > Gallery_en.properties > Gallery_en_US.properties > Gallery.properties
fr_FR: Gallery_fr_FR.properties > Gallery_fr.properties > Gallery_en_US.properties > Gallery_en.properties > Gallery.properties
ja: Gallery_ja.properties > Gallery_en_US.properties > Gallery_en.properties > Gallery.properties
2) en_CA: the bundle chosen, then keys from its parents
chosen bundle locale: en_CA
exit = Exit
gift = Gift shop on level {0}
hours = Open {0} to {1}
name = City Gallery
welcome = Welcome to {0}, {1}!
3) fr_FR: Gallery_fr wins, so en and en_US are never consulted
chosen bundle locale: fr
name = City Gallery (from Gallery.properties)
hours = <MissingResourceException: hours> (only in Gallery_en)
4) ja: no ja bundle, so the default locale's bundle is used
chosen bundle locale: en_US, name = The Gallery
5) no bundle at all
Menu for it_IT -> MissingResourceException
6) MessageFormat fills {0}, {1}, ...
Welcome to City Gallery, Priya!
Bienvenue au City Gallery, Priya !
Open 9:00 to {1}
Its {0} vs It's free
7) Properties
theme=dark, maxVisitors=250, tagline=Art for everyone
missing: null, with default: closed, get(): dark
Points to notice:
- For
en_CA,Gallery_en_CAexisted and was chosen.gift,welcome/hoursandname/exitcame from three different files along its chain. nameprintedCity Galleryfrom the base bundle, notThe Galleryfrom the default locale'sGallery_en_US.- The
fr_FRrequest choseGallery_fr, sohours, which exists only inGallery_en, threwMissingResourceException. jahad no bundle of its own, so the default locale'sGallery_en_USwas chosen, andnamecame from it.Menuhad only a French file. An Italian request with an English default found nothing, sogetBundlethrew."It's {0}"lost its apostrophe and its substitution, while"It''s {0}"worked.
Common questions
Where do bundle files go in a real project?
Anywhere on the class path (or module path), usually src/main/resources. Some teams package translations in a separate JAR, so adding a language doesn't mean rebuilding the application.
Are bundles cached?
Yes. getBundle caches loaded bundles, and ResourceBundle.clearCache() empties the cache. The example program clears it before each lookup.
Can modules use resource bundles?
Yes, but named modules locate them through ResourceBundleProvider services or by opening packages. Chapter 12 covers modules. The custom-Control overload used in the example program is meant for code on the class path.
Summary
- A resource bundle is a set of
Base[_lang[_COUNTRY]].propertiesfiles of key/value pairs, loaded withResourceBundle.getBundle(base[, locale]). - Bundle search: requested locale, then the default locale, then the base bundle, otherwise
MissingResourceException. - Values are inherited along the chosen bundle's parent chain only.
MessageFormat.formatfills{n}placeholders.'escapes text and''prints a quote.Propertiesstores string pairs.getProperty(key, default)supplies a fallback value.
Practice quiz
Test yourself with the resource bundles quiz: 10 exam-style questions with explanations.
You've finished Chapter 11. Check your understanding of the whole chapter with the Chapter 11 review quiz: 20 mixed questions on exception types, try/catch/finally, try-with-resources, formatting, locales and resource bundles.
Previous: Java Locales: Localizing Numbers, Currency, Percentages, Compact Numbers and Dates (OCP 21)
Next: Java Modules: Benefits, module-info.java, Compiling, Running and Packaging (OCP 21)
Related reading
- Java Locales: Localizing Numbers, Currency, Percentages, Compact Numbers and Dates (OCP 21)
- Java Formatting: DecimalFormat, DateTimeFormatter Patterns and String.format (OCP 21)
- Java try-with-resources: AutoCloseable, Closing Order and Suppressed Exceptions (OCP 21)
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
- Java Common Exception Classes: Runtime, Checked and Error Types on the Exam (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.