Locale ForLanguageTag BCP 47 Lookup
Locale.forLanguageTag parses BCP 47 tags and Locale.lookup picks the best match from user preferences, the same negotiation Accept-Language headers need.
Code
import java.util.List;
import java.util.Locale;
public class LanguageNegotiation {
public static void main(String[] args) {
// a BCP 47 tag parses into a Locale: region and script both fit
Locale parsed = Locale.forLanguageTag("zh-Hans-CN");
System.out.println("language=" + parsed.getLanguage() + " script=" + parsed.getScript());
// unparseable tags yield und (undetermined) instead of throwing
Locale broken = Locale.forLanguageTag("not a tag");
System.out.println("broken=" + broken);
// Accept-Language style negotiation: pick the best server-supported language by user priority
List<Locale.LanguageRange> preferences =
Locale.LanguageRange.parse("zh-CN, zh;q=0.8, en;q=0.6");
Locale chosen = Locale.lookup(preferences,
List.of(Locale.ENGLISH, Locale.CHINA));
System.out.println("chosen=" + chosen);
}
}What the demo negotiates
Locale.forLanguageTag parses zh-Hans-CN into a Locale whose language is zh and script is Hans, so both subtags survive the parse. A malformed input like “not a tag” does not throw; it yields Locale.ROOT — language, country and variant all empty strings — so the demo prints broken= with nothing after it. und and ROOT are semantically equivalent, but und itself is never printed.
The second half is content negotiation: LanguageRange.parse builds the priority list zh-CN, zh;q=0.8, en;q=0.6, and Locale.lookup walks it against the supported set of English and China. China wins because the user ranked zh-CN first, the same negotiation an Accept-Language header needs.
Points to remember
- lookup returns the first supported locale matching a preference, in user order.
- Unparseable tags fall back to Locale.ROOT, which prints as an empty string; und is the equivalent tag form.
Interactive Tools for This Topic
FAQ
- What does forLanguageTag do with garbage input?
- It returns the root locale (Locale.ROOT, all fields empty) rather than throwing; the demo prints broken= with nothing after it, since und maps to ROOT and never appears in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.