Saturday, 17 November 2012

Introduction To Java Internationalization

This post is a quick introduction/reminder about internationalization (i18n) in Java. The code examples are available from GitHub in the Java-Internationalization directory.


Making a Java application international is about dealing with:
  • Displayed text - Proper text according to user language.
  • Dates - Formatting, for example month, day year, or day, month, year?
  • Currencies - Using a comma or a dot as a separator? number of significant digits?


Localization is the process of adapting displayed text, dates and currencies to a country, region or language. Java defines the Locale class, which represents a language, and eventually a country or region associated to it.

The following describes how to list available Locale:
for ( Locale l : Locale.getAvailableLocales() ) {
    String s = l.getDisplayLanguage(Locale.ENGLISH)
        + " " + l.getDisplayCountry(Locale.ENGLISH);
The language and corresponding country is displayed (if available):
Japanese Japan
Spanish Peru

Resource Bundle & Property Files

ResourceBundles are created by providing a Locale. They contain objects and strings internationalized according to the provided locale.

Internationalized strings can be loaded from property files too:

Resource Bundles in Maven Java

Here is the content of MessageBundle_fr_FR:
greetings = Bonjour.
farewell = Au revoir.
inquiry = Comment allez-vous?
The following code describes how to create locales and load corresponding property files:
// Creating locales
Locale l_de_DE = new Locale("de", "DE");
Locale l_fr_FR = new Locale("fr", "FR");

// Resource bundles based on property files
ResourceBundle rb_de_DE
    = ResourceBundle.getBundle(

ResourceBundle rb_fr_FR
    = ResourceBundle.getBundle(

// Fetching translated text

Notice that one must provide the "package path" to load the property files.

The output is:
Wie geht's?
Comment allez-vous?

Dates & Currencies

In an earlier post, we have already described how to format currencies.

The following code describes how to format a date using locales:
// Creating locales
Locale l_de_DE = new Locale("de", "DE");
Locale l_fr_FR = new Locale("fr", "FR");

// Retrieving date formatters
DateFormat df_de_DE
    = DateFormat.getDateInstance(DateFormat.FULL, l_de_DE);

DateFormat df_fr_FR
    = DateFormat.getDateInstance(DateFormat.FULL, l_fr_FR);

Date date = new Date();

The output is:
Samstag, 17. November 2012
samedi 17 novembre 2012

More Java related posts here.