Locales in Java: Language Tags, Default Locales and Display Names
What a java.util.Locale is and how to get one right: BCP 47 language tags with scripts, regions and Unicode extensions, Locale.of and Locale.Builder, the default locale and its DISPLAY and FORMAT categories, display names, the Turkish i, and matching user preferences with LanguageRange.
kvi5hnuCode Sprout team member12 min readOn this page
Part 7 is about writing programs that work well for people all over the world. Java strings have been Unicode from the start, but Unicode alone does not make a program international. People in different places write numbers, dates and money differently, sort words by different rules, and of course read different languages. In Java, all of those preferences hang off one small object: java.util.Locale. This article explains what a locale contains, how to build one correctly, where the default comes from, and what you can do with a locale directly. The following articles feed locales into number, date, collation, message and resource-bundle APIs.
Why a language is not enough
The same value looks different depending on where the reader is:
| Locale | 123456.78 | Same date |
|---|---|---|
| English, United States | 123,456.78 | 3/22/61, March 22, 1961 |
| German, Germany | 123.456,78 | 22.03.61, 22. März 1961 |
| German, Switzerland | 123’456.78 | 22.03.61, 22. März 1961 |
| French, France | 123 456,78 (narrow no-break space) | 22/03/1961, 22 mars 1961 |
| Chinese, China | 123,456.78 | 1961/3/22, 1961年3月22日 |
German speakers in Germany and Switzerland share a language but not a number format or a currency. That is why a locale usually combines a language with a region, and why it can carry extra preferences on top.
What is inside a Locale
A locale has up to five parts, written as a language tag as defined by IETF BCP 47 (RFC 5646):

- Language: two or three lower-case letters from ISO 639, such as
en,de,zh,hi. This is the only required part. - Script (optional): four letters, first one upper-case, from ISO 15924, such as
Latn,Cyrl,Hant(traditional Chinese) orHans(simplified Chinese). Serbian, for instance, is written in both Latin and Cyrillic. - Region (optional): two upper-case letters from ISO 3166 (
US,CH,IN) or a three-digit UN M.49 code such as419for Latin America. - Variant (optional): rarely used today. Things that used to be variants, like the Norwegian Nynorsk spelling or Thai digits, now have their own language code (
nn) or an extension. - Extensions (optional): a single letter, then key/value pairs. The
uextension holds Unicode locale preferences:ca(calendar, e.g.ca-japanese),nu(numbering system, e.g.nu-thai),co(collation),hc(hour cycle),fw(first day of week),rg(region override) and more. Thexextension is for private use.
Some common codes:
| Language | Code | Region | Code |
|---|---|---|---|
| Chinese | zh | China / Taiwan | CN / TW |
| English | en | United States / United Kingdom | US / GB |
| French | fr | France / Canada | FR / CA |
| German | de | Germany / Austria / Switzerland | DE / AT / CH |
| Hindi | hi | India | IN |
| Japanese | ja | Japan | JP |
| Portuguese | pt | Brazil / Portugal | BR / PT |
| Spanish | es | Spain / Mexico / Latin America | ES / MX / 419 |
Some codes look odd because they come from the name in the language itself: de from Deutsch, zh from zhōngwén, and CH from the Latin Confoederatio Helvetica.
Getting a Locale object
There are four ways, and the right choice depends on where the information comes from.
Locale usEnglish = Locale.forLanguageTag("en-US"); // from a tag (HTTP header, config file)
Locale swissGerman = Locale.of("de", "CH"); // language [, region [, variant]] (Java 19)
Locale serbianLatn = new Locale.Builder() // validated, supports script and extensions
.setLanguage("sr").setScript("Latn").setRegion("RS").build();
Locale us = Locale.US; // predefined constant
Locale.forLanguageTag(tag)parses a BCP 47 tag, including scripts and extensions. It never throws: an ill-formed tag yields as much as it could parse, possibly nothing at all, which prints asund(undetermined)."english_US"becomesund.Locale.of(language[, country[, variant]]), added in Java 19, replaced theLocaleconstructors, which are now deprecated. It does no validation:Locale.of("english")happily creates a locale whose language isenglish.Locale.Buildervalidates each part and throwsIllformedLocaleExceptionfor something likesetLanguage("english"). It is the only way, besides a tag, to set a script or extensions. Use it when you assemble locales from separate fields.- Constants exist for country locales (
US,UK,CANADA,CANADA_FRENCH,FRANCE,GERMANY,ITALY,JAPAN,KOREA,CHINA/PRC,TAIWAN) and language-only locales (ENGLISH,FRENCH,GERMAN,ITALIAN,JAPANESE,KOREAN,CHINESE,SIMPLIFIED_CHINESE,TRADITIONAL_CHINESE).Locale.ROOThas an empty language and stands for language-neutral behaviour.
To go back to a tag, call toLanguageTag(). Do not use toString() for that: it produces the older underscore form, and for a locale with a script it gives sr_RS_#Latn, which no other system understands. Locale.caseFoldLanguageTag (Java 21) normalizes the case of a tag string (ZH-hant-tw becomes zh-Hant-TW) without creating a locale.
The accessors return the parts: getLanguage(), getScript(), getCountry(), getVariant(), getUnicodeLocaleKeys(), getUnicodeLocaleType("nu"), getExtension('u'), plus getISO3Language() and getISO3Country() for three-letter codes (deu, CHE).
To list what is known, Locale.getAvailableLocales() returns an array and Locale.availableLocales() (Java 21) a stream. Locale.getISOLanguages() and Locale.getISOCountries() return all two-letter codes, and getISOCountries(Locale.IsoCountryCode.PART1_ALPHA3) returns three-letter ones.
The default locale
When a locale-sensitive method is called without a locale, it uses a default. The JVM computes the default at startup from the operating system (on Linux from the LC_ALL, LC_CTYPE/LC_MESSAGES and LANG variables, on Windows and macOS from the user settings) and stores it in the system properties user.language, user.script, user.country/user.region, user.variant and user.extensions.
There is not just one default. Locale.Category distinguishes two:
DISPLAY: the language of the user interface, used for things likegetDisplayName()and resource bundles.FORMAT: used to format numbers, dates and currencies, byNumberFormat,DateTimeFormatter,String.formatand friends.
A French speaker living in Canada might want French menus with Canadian number formats. Read the defaults with Locale.getDefault(Locale.Category.FORMAT) and so on; plain Locale.getDefault() returns the general default. You can override them at launch:
java -Duser.language=de -Duser.region=CH MyApp
java -Duser.language=fr -Duser.language.format=en -Duser.country.format=CA MyApp
java -XshowSettings:locale -version prints the defaults the JVM picked, which is a quick way to check. You can also change them in code with Locale.setDefault(locale) and Locale.setDefault(category, locale). setDefault(locale) resets both categories too.
On Linux, the FORMAT default comes from LC_CTYPE and the DISPLAY default from LC_MESSAGES (each overridden by LC_ALL, falling back to LANG); the finer variables LC_NUMERIC, LC_MONETARY and LC_TIME are ignored. Since JDK 9 the locale data come from the Unicode CLDR; the older JRE/COMPAT data, which could be selected with -Djava.locale.providers=COMPAT, were removed in JDK 23.
The ultimate locale-sensitive bug: the Turkish i
Most locale-dependent methods are obvious: formatting numbers and dates. Some are not. String.toUpperCase() and toLowerCase() without an argument use the default locale, and Turkish has a dotted and a dotless i: "title".toUpperCase(Locale.forLanguageTag("tr-TR")) is TİTLE with a dotted capital İ, not TITLE. Programs that upper-case identifiers, HTTP header names or enum names before comparing them break as soon as they run on a Turkish machine.
For anything that is not shown to a person, write toUpperCase(Locale.ROOT), or compare with equalsIgnoreCase, which works character by character and does not depend on the locale. The same reasoning applies to String.format (%,.2f uses the FORMAT default) and to number parsing.
Display names
A locale knows how to describe itself to a person: getDisplayName() returns a readable name instead of codes. The name is written in the DISPLAY default locale unless you pass one:
Locale.of("de", "CH").getDisplayName(Locale.ENGLISH) // German (Switzerland)
Locale.of("de", "CH").getDisplayName(Locale.GERMAN) // Deutsch (Schweiz)
There are also getDisplayLanguage, getDisplayScript, getDisplayCountry and getDisplayVariant. When you present a language picker, show each language in itself (locale.getDisplayLanguage(locale)): Deutsch, français, हिन्दी, русский. A user who cannot read the current interface language can still find their own.
Matching what the user wants with what you have
Users often have a ranked list of languages, such as the HTTP Accept-Language header fr-CH, fr;q=0.9, en;q=0.8, *;q=0.5. The application supports a fixed set. Java implements the matching algorithms of RFC 4647:
Locale.LanguageRange.parse(String)turns the header into weighted ranges.Locale.filter(ranges, locales)returns every supported locale that matches some range, best first. It is good for building a fallback list.Locale.lookup(ranges, locales)returns the single best match, ornull. Lookup truncates a range from the end (fr-CH, thenfr) and requires an exact match. With supported localesen-US,fr-FRandde-DE, the rangefrdoes not matchfr-FR, so the result isnull, whilefilterfindsfr-FRfirst. Offer language-only locales (fr) when you rely on lookup.filterTagsandlookupTagdo the same for strings.
ResourceBundle (article 76) has its own fallback logic, but for web applications these methods are the standard way to choose the locale in the first place.
The program
The demo builds locales in each way, shows how lenient tag parsing is, formats the same number in several locales, prints display names, demonstrates the Turkish i and the two default categories (restoring the original default at the end), and runs the RFC 4647 matching methods. The French grouping separator is a narrow no-break space and is shown as <NNBSP>.
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;
public class Solution {
public static void main(String[] args) {
System.out.println("== Building locales ==");
Locale usEnglish = Locale.forLanguageTag("en-US");
Locale swissGerman = Locale.of("de", "CH");
Locale serbianLatin = new Locale.Builder()
.setLanguage("sr").setScript("Latn").setRegion("RS").build();
Locale thaiDigits = Locale.forLanguageTag("th-TH-u-nu-thai");
Locale japaneseCal = Locale.forLanguageTag("ja-JP-u-ca-japanese");
for (Locale loc : List.of(usEnglish, swissGerman, serbianLatin, thaiDigits, japaneseCal)) {
System.out.printf("%-22s lang=%s script=%s region=%s ext=%s%n",
loc.toLanguageTag(), loc.getLanguage(), loc.getScript(),
loc.getCountry(), loc.getUnicodeLocaleKeys());
}
System.out.println("toString vs tag: " + serbianLatin + " / " + serbianLatin.toLanguageTag());
System.out.println("number type of th-TH-u-nu-thai: " + thaiDigits.getUnicodeLocaleType("nu"));
System.out.println("\n== Tags are normalized, not validated ==");
System.out.println(Locale.forLanguageTag("EN-us").toLanguageTag());
System.out.println("bogus tag -> '" + Locale.forLanguageTag("english_US").toLanguageTag() + "'");
System.out.println("Locale.of(\"english\") language: " + Locale.of("english").getLanguage());
System.out.println("caseFoldLanguageTag: " + Locale.caseFoldLanguageTag("ZH-hant-tw"));
try {
new Locale.Builder().setLanguage("english").build();
} catch (IllformedLocaleException e) {
System.out.println("Builder rejects 'english': " + e.getMessage());
}
System.out.println("old code iw -> " + Locale.of("iw").getLanguage()
+ ", he -> " + Locale.forLanguageTag("he").getLanguage());
System.out.println("ROOT tag: " + Locale.ROOT.toLanguageTag() + ", empty language: '"
+ Locale.ROOT.getLanguage() + "'");
System.out.println("\n== Same number, different locales ==");
double amount = 123456.78;
for (Locale loc : List.of(Locale.US, Locale.GERMANY, swissGerman, Locale.FRANCE,
Locale.forLanguageTag("en-IN"), thaiDigits)) {
System.out.printf("%-16s %s%n", loc.toLanguageTag(),
visible(NumberFormat.getNumberInstance(loc).format(amount)));
}
System.out.println("\n== Display names ==");
for (Locale in : List.of(Locale.ENGLISH, Locale.GERMAN, Locale.JAPANESE)) {
System.out.println(in.getLanguage() + ": " + swissGerman.getDisplayName(in)
+ " | " + serbianLatin.getDisplayName(in));
}
System.out.println("language only: " + swissGerman.getDisplayLanguage(Locale.FRENCH)
+ ", country only: " + swissGerman.getDisplayCountry(Locale.FRENCH));
System.out.println("each in its own language: " + List.of(Locale.GERMAN, Locale.FRENCH,
Locale.forLanguageTag("hi"), Locale.forLanguageTag("ru")).stream()
.map(l -> l.getDisplayLanguage(l)).collect(Collectors.joining(", ")));
System.out.println(japaneseCal.getDisplayName(Locale.ENGLISH));
System.out.println("ISO3: " + swissGerman.getISO3Language() + "/" + swissGerman.getISO3Country());
System.out.println("\n== The Turkish i ==");
Locale turkish = Locale.forLanguageTag("tr-TR");
String key = "title";
System.out.println("toUpperCase(tr) : " + key.toUpperCase(turkish));
System.out.println("toUpperCase(ROOT) : " + key.toUpperCase(Locale.ROOT));
System.out.println("equal ignoring case after tr upper? "
+ "TITLE".equals(key.toUpperCase(turkish)));
System.out.println("\n== Default locale per category ==");
Locale saved = Locale.getDefault();
try {
Locale.setDefault(Locale.US);
Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY);
System.out.println("default=" + Locale.getDefault()
+ " DISPLAY=" + Locale.getDefault(Locale.Category.DISPLAY)
+ " FORMAT=" + Locale.getDefault(Locale.Category.FORMAT));
System.out.println("NumberFormat follows FORMAT: "
+ NumberFormat.getInstance().format(amount));
System.out.println("getDisplayName() follows DISPLAY: " + swissGerman.getDisplayName());
System.out.println("String.format uses FORMAT: " + String.format("%,.2f", amount));
} finally {
Locale.setDefault(saved);
}
System.out.println("\n== Matching user preferences (RFC 4647) ==");
List<Locale.LanguageRange> prefs =
Locale.LanguageRange.parse("fr-CH, fr;q=0.9, en;q=0.8, *;q=0.5");
System.out.println("ranges: " + prefs.stream()
.map(r -> r.getRange() + "=" + r.getWeight()).collect(Collectors.joining(" ")));
List<Locale> supported = List.of(Locale.forLanguageTag("en-US"),
Locale.forLanguageTag("fr-FR"), Locale.forLanguageTag("de-DE"));
System.out.println("filter: " + Locale.filter(prefs, supported));
System.out.println("lookup: " + Locale.lookup(prefs, supported));
List<String> tags = List.of("en-US", "fr", "de");
System.out.println("lookupTag: " + Locale.lookupTag(prefs, tags));
System.out.println("\n== Inventory ==");
System.out.println("ISO languages: " + Locale.getISOLanguages().length
+ ", ISO countries: " + Locale.getISOCountries().length);
System.out.println("Locale.availableLocales() contains de-CH: "
+ Locale.availableLocales().anyMatch(swissGerman::equals));
System.out.println("Alpha-3 countries include DEU: "
+ Locale.getISOCountries(Locale.IsoCountryCode.PART1_ALPHA3).contains("DEU"));
}
static String visible(String s) {
return s.replace("\u202f", "<NNBSP>").replace("\u00a0", "<NBSP>").replace("’", "’");
}
}
== Building locales ==
en-US lang=en script= region=US ext=[]
de-CH lang=de script= region=CH ext=[]
sr-Latn-RS lang=sr script=Latn region=RS ext=[]
th-TH-u-nu-thai lang=th script= region=TH ext=[nu]
ja-JP-u-ca-japanese lang=ja script= region=JP ext=[ca]
toString vs tag: sr_RS_#Latn / sr-Latn-RS
number type of th-TH-u-nu-thai: thai
== Tags are normalized, not validated ==
en-US
bogus tag -> 'und'
Locale.of("english") language: english
caseFoldLanguageTag: zh-Hant-TW
old code iw -> he, he -> he
ROOT tag: und, empty language: ''
== Same number, different locales ==
en-US 123,456.78
de-DE 123.456,78
de-CH 123’456.78
fr-FR 123<NNBSP>456,78
en-IN 123,456.78
th-TH-u-nu-thai ๑๒๓,๔๕๖.๗๘
== Display names ==
en: German (Switzerland) | Serbian (Latin, Serbia)
de: Deutsch (Schweiz) | Serbisch (Lateinisch, Serbien)
ja: ドイツ語 (スイス) | セルビア語 (ラテン文字、セルビア)
language only: allemand, country only: Suisse
each in its own language: Deutsch, français, हिन्दी, русский
Japanese (Japan, Japanese Calendar)
ISO3: deu/CHE
== The Turkish i ==
toUpperCase(tr) : TİTLE
toUpperCase(ROOT) : TITLE
equal ignoring case after tr upper? false
== Default locale per category ==
default=en_US DISPLAY=en_US FORMAT=de_DE
NumberFormat follows FORMAT: 123.456,78
getDisplayName() follows DISPLAY: German (Switzerland)
String.format uses FORMAT: 123.456,78
== Matching user preferences (RFC 4647) ==
ranges: fr-ch=1.0 fr=0.9 en=0.8 *=0.5
filter: [fr_FR, en_US, de_DE]
lookup: null
lookupTag: fr
== Inventory ==
ISO languages: 188, ISO countries: 249
Locale.availableLocales() contains de-CH: true
Alpha-3 countries include DEU: true
The Indian English line shows a limitation of NumberFormat: Indian convention groups as 1,23,456.78, but DecimalFormat supports only a single grouping size, so you get Western grouping. Article 72 covers number formatting in detail.
Common questions
How do I get the user's locale in a web application?
From the HTTP Accept-Language header, parsed with Locale.LanguageRange.parse and matched against your supported locales with Locale.lookup or filter. Then let users override it in their settings, and store the choice. Never use the server's default locale for a user.
What's the difference between Locale.ROOT, Locale.ENGLISH and Locale.US?
ROOT is the neutral locale: language-independent behavior for case mapping, and the base for resource bundles. ENGLISH is the English language without region rules. US adds United States conventions, such as the dollar and month-first dates. For machine-readable output, use ROOT.
Why does new Locale("en", "US") give a deprecation warning?
The Locale constructors are deprecated since Java 19. Use Locale.of("en", "US") (Java 19), Locale.forLanguageTag("en-US"), or a Locale.Builder, which validates its input.
Should I use toString() or toLanguageTag() to store a locale?
toLanguageTag(), and restore it with forLanguageTag. It's the standard BCP 47 form that browsers, databases and other languages understand.
How do I make sure my program doesn't depend on the machine's locale?
Pass locales explicitly in all formatting and case-conversion calls in non-UI code, and test with an unusual default, for example -Duser.language=tr -Duser.country=TR (the Turkish i) or de (comma as decimal separator). Static analysis tools such as Error Prone flag calls that use the default locale.
API reference
| Method | Purpose |
|---|---|
Locale.forLanguageTag(String), toLanguageTag() | convert from and to BCP 47 tags |
Locale.of(lang[, country[, variant]]) (19) | factory replacing the deprecated constructors |
new Locale.Builder().setLanguage/Script/Region/Variant/Extension/UnicodeLocaleKeyword(...).build() | validated construction |
getLanguage, getScript, getCountry, getVariant, getUnicodeLocaleType, getExtension | parts |
getDisplayName([inLocale]), getDisplayLanguage, getDisplayCountry, getDisplayScript | names for people |
Locale.getDefault([Category]), Locale.setDefault([Category,] locale) | default locales |
Locale.getAvailableLocales(), availableLocales() (21) | installed locales |
getISOLanguages(), getISOCountries([IsoCountryCode]), getISO3Language(), getISO3Country() | ISO code lists |
Locale.caseFoldLanguageTag(String) (21) | normalize a tag string |
LanguageRange.parse, Locale.filter, lookup, filterTags, lookupTag | RFC 4647 matching |
Locale.ROOT | language-neutral locale for machine text |
Summary
- A locale is a language plus optional script, region, variant and extensions, written as a BCP 47 tag like
sr-Latn-RSorth-TH-u-nu-thai. - Create locales with
forLanguageTag,Locale.of(Java 19),Locale.Builder(validated) or the constants; convert back withtoLanguageTag, nottoString. forLanguageTagandLocale.ofdo not validate; onlyLocale.Builderrejects bad input.- There are separate DISPLAY and FORMAT defaults. Use them for user-facing text, and pass
Locale.ROOTor an explicit locale for anything machine-readable. - Locale-sensitive surprises include
toUpperCase()in Turkish andString.formatin German. - Show language choices in their own language with
getDisplayLanguage(locale). - Match user preferences to supported locales with
LanguageRange,filterandlookup.
Practice Questions
1. What is the difference between Locale.forLanguageTag("en_US") and Locale.forLanguageTag("en-US")?
Language tags use hyphens. en-US parses as English, United States. en_US is not a well-formed tag; forLanguageTag does not throw but stops at the first bad subtag, and since that is the very first one you get the empty "undetermined" locale (toLanguageTag() returns und) instead of English (US). The underscore form is what Locale.toString() produces, which is why mixing the two causes bugs. Always store and exchange tags produced by toLanguageTag().
2. A config value "pt-BR" must become a Locale, and invalid values must be rejected. Which API should you use?
forLanguageTag never throws and Locale.of does not validate, so neither can reject bad input. Use new Locale.Builder().setLanguageTag(value).build(), which throws IllformedLocaleException for ill-formed tags. You can additionally check that the result is in your set of supported locales.
3. A server converts header names with name.toUpperCase() and compares them to "CONTENT-TYPE". Why does it fail on some machines?
toUpperCase() uses the default locale. In Turkish (tr) and Azerbaijani (az), lower-case i upper-cases to dotted İ, so the result is not equal to the expected ASCII string. Use toUpperCase(Locale.ROOT) or equalsIgnoreCase.
4. A user interface should be in French but numbers formatted the Canadian English way. How do you express that in Java?
Set different defaults for the two categories: Locale.setDefault(Locale.Category.DISPLAY, Locale.FRENCH) and Locale.setDefault(Locale.Category.FORMAT, Locale.CANADA), or at launch with -Duser.language=fr -Duser.language.format=en -Duser.country.format=CA. Even better, keep two explicit locales in the user's session and pass them to formatters and bundles.
5. The supported locales are en-US, fr-FR and de-DE, and the browser sends "fr-CH, fr;q=0.9". Why does Locale.lookup return null, and what can you do?
Lookup removes subtags from the end of each range (fr-CH then fr) and looks for an exact match among the available locales. Neither fr-CH nor fr equals fr-FR, so nothing matches. Either use Locale.filter, which treats fr as matching fr-FR and returns [fr_FR, ...], or add the language-only locale fr to the supported list.
Previous: Formatting and Parsing Dates in Java, and Converting Legacy Date and Calendar
Next: Number Formats in Java: NumberFormat, Compact Numbers, DecimalFormat and Currencies
Related reading
- Formatting and Parsing Dates in Java, and Converting Legacy Date and Calendar
- LocalTime, ZonedDateTime and Daylight Saving Time in Java
- LocalDate, Period and Temporal Adjusters in Java
- Instant and Duration in Java: Points and Spans on the Time Line
- Connection Pools, DataSources and JPA: JDBC in Real Applications

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.