55

I have all my ResourceBundle values in a table and formatted as per requirement. I have to change the languages on the website based on user selection in a dropdown at the top of the page.

If I use a language code such as en_US, then it works fine. If I use en-US as a language code, then it doesn't work. What might be the problem? Which is the correct way to do this?

4 Answers 4

50

"en-US" is an IETF language tag. While Java'a Locale class was clearly based on IETF language tags, it uses underscores in place of hyphens when separating language codes from country codes (and also variants), so calling toString() on the equivalent Locale will give you en_US.

As of Java 7 you can use Locale.forLanguageTag(String) and toLanguageTag() to convert between language tags and Locale objects.

When converting strings to Locale objects it's a good idea to normalize by splitting components on hyphens and underscores, lowercasing the first component (the language code) and upper-casing the second component (the country code).

1
  • 1
    This answer is the best response for what to do in java code. For other languages/frameworks, not so much. When making calls between frameworks with different conventions, you have a "pratfall" of the coder needing to know a conversion is required. recommend using the convention of the framework you are calling from. When you are making calls to another framework, provide "proxies" that do the conversion. Why? it eliminates the need to know that the called framework uses a different convention. Contributors will ONLY "see" one convention using that one will avoid the pratfall.
    – DaBlick
    Commented Jan 5, 2018 at 15:01
36

"en" is the language code specified by ISO 639. while US is country code specified by 3166.
In Java, the Locale object recognizes the language as languageCode_countryCode (e.g. en_US) and not as languageCode-countryCode.

1
  • But there is no constructor for lang_country
    – eastwater
    Commented Jan 9, 2023 at 16:54
7

Or you could use Locale us = Locale.forLanguageTag("en-US") and us.toLanguageTag(), and that will do the conversion for you without having to create your own error-prone implementation.

4

As of Java8, initializing the locale should be done using the language tag en-US. Locale.forLanguageTag("en-US").toString(); returns the output: en_US

Where as Locale.forLanguageTag("en_US") does not create the required locale. It will default to the system locale. Locale.forLanguageTag("en_US").toString() returns null

1
  • What is the reason, toString() uses underscore _? Inconsistency with language tag
    – eastwater
    Commented Jan 9, 2023 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.