Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 201 Β· Working with Data

Locales and Internationalization

Format numbers, currencies, percentages and dates for any country with Java's Locale, load translations with ResourceBundle, and avoid the Turkish i and other locale bugs.

The number one thousand two hundred thirty-four and a half is written 1,234.5 in the United States, 1.234,5 in Germany, 1 234,5 in France and 1,234.5 again in Japan. The date October 5 is 10/5/25 to an American and 05/10/25 to a Brit. A program that prints numbers and dates with one fixed format looks wrong, or worse, gets misread, everywhere else. Internationalization (often shortened to i18n: an "i", 18 letters, an "n") means writing code that adapts formats and text to the user's language and region instead of hardcoding them.

Java has built-in support for hundreds of languages and regions, using the Unicode CLDR data that browsers and phones also use. This lesson covers the Locale class, locale-aware number, currency and date formatting, parsing user input in local formats, translated messages with ResourceBundle and MessageFormat, and the classic bugs that appear when locale-sensitive methods are used for machine-readable text.

The Locale class

A java.util.Locale identifies a language, optionally with a region (country) and a few other details. It doesn't do anything by itself; you pass it to formatting methods, which then follow that locale's conventions:

Java Creating and describing locales

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What to remember:

  • Create locales with Locale.of(language, country) (Java 19+) or Locale.forLanguageTag("pt-BR"). The old new Locale(...) constructors are deprecated. Language codes are lowercase (fr), country codes uppercase (CA).
  • Language tags like en-US, pt-BR or zh-Hant-TW are the standard text form, used in HTTP Accept-Language headers and HTML lang attributes. Convert with forLanguageTag and toLanguageTag.
  • Constants exist for common locales: Locale.US, Locale.UK, Locale.GERMANY, Locale.FRANCE, Locale.JAPAN, and Locale.ROOT, the neutral locale for machine-readable text.
  • Locale.getDefault() comes from the operating system. A server's default locale says nothing about the user, who might be on the other side of the world. In web apps, take the locale from the request or the user's profile and pass it explicitly.

Formatting numbers, currencies and percentages

java.text.NumberFormat produces localized number text. Ask it for the kind of formatter you need:

Java One number, many countries

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look closely at the output. The grouping separator is a comma in the US, a period in Germany, a narrow no-break space in France and a typographic apostrophe (’) in Switzerland. The currency symbol goes before or after the number, sometimes with a space, and the yen is rounded to a whole number because it has no minor unit. Your code didn't need to know any of that.

One honest limitation shows up in the Hindi (India) row. Indian convention groups digits in twos after the first thousand (lakh and crore: 12,34,567), but java.text.DecimalFormat supports only one grouping size, so the JDK prints 1,234,567. If you serve Indian users, the ICU4J library formats it correctly.

Practical notes:

  • The currency formatter uses the locale's currency. It doesn't convert money: formatting euros with Locale.US would label them as dollars. When the currency is part of your data, set it explicitly with format.setCurrency(Currency.getInstance("EUR")).
  • getCompactNumberInstance (Java 12) produces short forms like 1K and 3M, as seen on social media counters.
  • NumberFormat objects are not thread-safe. Create one per use or per thread, rather than sharing a static instance between threads.
  • For exact money values, format a BigDecimal instead of a double; NumberFormat accepts both. See BigInteger and BigDecimal.
  • String.format and printf are locale-sensitive too: String.format(Locale.GERMANY, "%.2f", 3.5) gives 3,50. Without a locale argument they use the default locale, which matters below.

The Currency class

java.util.Currency describes ISO 4217 currencies: their code, how many decimal places they use and how each locale writes their symbol.

Java
Currency yen = Currency.getInstance("JPY");
yen.getDefaultFractionDigits();          // 0: no cents
Currency.getInstance("EUR").getSymbol(Locale.FRANCE);   // "€"
Currency.getInstance("USD").getSymbol(Locale.CANADA);   // "US$": Canadians need to know which dollar
Currency.getInstance(Locale.of("pt", "BR"));            // BRL

Parsing numbers that users type

Formatting has a mirror image: a German user types 1.234,5 and means one thousand two hundred thirty-four and a half. Double.parseDouble only understands the machine format, so use NumberFormat.parse with the user's locale:

Java Parsing localized input

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The surprise is the third line: parse("12abc") happily returns 12. For validation, use the ParsePosition overload and check that the whole string was consumed, as the last lines do. Also note that the German formatter reads 1.234 as one thousand two hundred thirty-four, while a US formatter reads the same text as one point two three four, so always parse with the locale the user actually typed in.

Dates and times in the user's language

The java.time formatters from Dates and Times are locale-aware too. Two approaches work:

Java Localized date formats and names

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • Localized styles (ofLocalizedDate, ofLocalizedTime, ofLocalizedDateTime with SHORT, MEDIUM, LONG, FULL) let each locale choose the order, separators and words. Prefer them for anything shown to people.
  • Patterns (ofPattern("d MMMM yyyy", locale)) fix the layout but still translate names. Always pass the locale; without it, the default locale fills in the month names.
  • The Egyptian Arabic date looks plain, but it contains invisible right-to-left marks (U+200F) next to the slashes so it displays correctly inside right-to-left text. Never parse localized output with string tricks; use the same formatter to parse it.
  • For data exchange (JSON, logs, databases), don't localize at all: use ISO-8601 (2025-10-05), which LocalDate.toString() already produces.

Translated messages with ResourceBundle

Formats are only half the job; the words themselves need translating. Java's standard mechanism is the ResourceBundle: a set of key/value lookups, one per language, chosen automatically for a locale. Real projects usually store translations in .properties files:

PROPERTIES
# messages.properties (the base bundle, used when nothing better exists)
greeting=Hello, {0}!
cart=You have {0,choice,0#no items|1#one item|1<{0,number,integer} items} in your cart.

# messages_de.properties
greeting=Hallo, {0}!
cart=Sie haben {0,choice,0#keine Artikel|1#einen Artikel|1<{0,number,integer} Artikel} im Warenkorb.

You load them with ResourceBundle.getBundle("messages", locale). Properties files need a real project with a classpath (see Properties Files and Configuration), so this demo uses the other kind of bundle, a ListResourceBundle class, which works in a single file and behaves the same way:

Java ResourceBundle lookup and fallback

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

How the lookup works:

  • getBundle(base, locale) searches from the most specific name to the least: Messages_de_AT, then Messages_de, then the base Messages. That's why Austria (de-AT) gets the German bundle, and Japanese, with no bundle of its own, falls back to the base. (The printed bundle locale is empty for the base bundle.)
  • Lookups also fall back key by key: the German bundle has no logout, so its parent, the base bundle, supplies Log out. A missing key everywhere throws MissingResourceException.
  • Before falling back to the base, getBundle also tries the JVM's default locale. The demo sets the default to Locale.ROOT to keep the result predictable; on a server whose default is German, a Japanese user would otherwise get German. Use ResourceBundle.Control.getNoFallbackControl(...) if you never want that.
  • MessageFormat fills in , placeholders and can format numbers, dates and choices. The choice format picks different text for 0, 1 and more, so you never print "1 items". Many languages have more plural forms than English (Polish, Arabic, Russian), so large projects often use the ICU4J library for full plural rules.
  • Never build sentences by concatenating translated fragments: word order differs between languages. Translate whole sentences with placeholders.

In a normal project you'd write messages_de.properties files instead of classes, and the lookup rules are identical. Frameworks like Spring (see Advanced Java) build on the same mechanism.

The Turkish i and other locale traps

Locale-sensitive methods are a classic source of bugs when the text isn't for humans. The famous example is Turkish, which has two letter i's: dotted i/Δ° and dotless Δ±/I. So in Turkish, the uppercase of i is Δ°, and the lowercase of I is Δ±:

Java When toLowerCase breaks your program

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

On a computer set to Turkish, "INFO".toLowerCase() becomes Δ±nfo, so a command parser, an HTTP header check or an enum lookup that worked everywhere else suddenly fails. Similarly, a German default locale turns 9.99 into 9,99 and produces invalid JSON. These bugs only appear for users in certain countries, which makes them hard to reproduce.

The rules that prevent them:

  • For machine-readable text (keywords, identifiers, file formats, protocols, JSON, SQL, config keys), use Locale.ROOT: toLowerCase(Locale.ROOT), toUpperCase(Locale.ROOT), String.format(Locale.ROOT, ...).
  • For case-insensitive comparisons, equalsIgnoreCase compares character by character without locale rules, so it's safe for keywords.
  • For text shown to people, use the user's locale explicitly.
  • Integer.toString, Double.toString, parseInt and parseDouble are locale-independent, which is what you want for data.
  • Sorting words alphabetically is locale-sensitive as well: use a Collator, as shown in Comparing and Converting Strings.

Internationalization checklist

  • Keep user-visible text out of code; put it in resource bundles with whole-sentence keys.
  • Store data in neutral forms (UTC instants, ISO dates, BigDecimal amounts plus a currency code) and localize only when displaying.
  • Pass the locale explicitly to every formatter; don't rely on the server's default.
  • Use Locale.ROOT for anything a program will read back.
  • Use UTF-8 everywhere, so every language's characters survive storage and transfer (Character Sets and Encoding).
  • Test with a few demanding locales: German (long words, comma decimals), Turkish (i), Arabic (right to left), Japanese (no spaces, different scripts) and Hindi (lakh grouping, which needs ICU4J).

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does NumberFormat.getNumberInstance(Locale.GERMANY).format(1234.5) return?

    German uses a period for grouping thousands and a comma as the decimal separator.
  2. 2. A program runs on a server whose default locale is Turkish. What does "FILE".toLowerCase() return?

    In Turkish, the lowercase of I is the dotless Δ±. Use toLowerCase(Locale.ROOT) for machine-readable text.
  3. 3. There are bundles Messages and Messages_fr. With a default locale of ROOT, which one does getBundle("Messages", Locale.of("fr", "CA")) return?

    The lookup tries Messages_fr_CA first, then Messages_fr, which exists, so French Canadians get the French bundle.
  4. 4. What does NumberFormat.getNumberInstance(Locale.US).parse("42 apples") do?

    parse stops at the first character it can't use and returns what it read. Use the ParsePosition overload to check that the whole input was consumed.
  5. 5. Why does the cart message use {0,choice,0#no items|1#one item|1<...} instead of "{0} items"?

    The choice format picks different text depending on the number, avoiding mistakes like "1 items". Other languages need different plural forms, which translators can express the same way.

Summary

  • A Locale names a language and region; create it with Locale.of or Locale.forLanguageTag, and pass it explicitly instead of relying on the JVM default.
  • NumberFormat formats and parses numbers, currencies, percentages and compact numbers in local style; parse user input with the user's locale and check the ParsePosition.
  • DateTimeFormatter.ofLocalizedDate(...) and patterns with a locale produce dates in the user's language; use ISO-8601 for data.
  • ResourceBundle picks translations from the most specific matching bundle and falls back key by key; MessageFormat fills placeholders and handles plurals with choice.
  • Locale-sensitive methods break machine text: use Locale.ROOT for case conversion and formatting of keywords, JSON, SQL and file formats.

Next: Reading and Writing Files, where you'll save data to disk and read it back with Path and Files.