Working with Internationalization and Localization
1. Understanding Locale Class
| Element | Detail |
|---|---|
| Identifies | Language + country + variant |
| Constant | Locale.US, Locale.JAPAN, etc. |
| Default | Locale.getDefault() |
2. Creating Locales
| Form | Example |
|---|---|
| Constructor | Locale.of("en", "US") (Java 19+) |
| Tag | Locale.forLanguageTag("en-US") |
| Builder | new Locale.Builder().setLanguage("fr").build() |
3. Using ResourceBundle
Example: Resource bundle
// messages_en_US.properties: greeting=Hello, {0}!
// messages_fr_FR.properties: greeting=Bonjour, {0}!
ResourceBundle bundle = ResourceBundle.getBundle("messages", Locale.FRANCE);
String fmt = bundle.getString("greeting");
String msg = MessageFormat.format(fmt, "Alice");
| Aspect | Detail |
|---|---|
| File naming | basename_lang_COUNTRY.properties |
| Fallback | Locale → language → default → root |
| Java class bundle | Extend ListResourceBundle |
4. Loading Resource Bundles
| Method | Detail |
|---|---|
getBundle(name) | Default locale |
getBundle(name, locale) | Specific locale |
getBundle(name, locale, classloader) | Custom CL |
5. Formatting Numbers
| Form | Example |
|---|---|
NumberFormat.getInstance(loc) | Default |
NumberFormat.getNumberInstance(loc) | Plain |
NumberFormat.getPercentInstance(loc) | Percent |
NumberFormat.getCompactNumberInstance() JAVA 12+ | 1.5K, 2M |
6. Formatting Currencies
Example: Currency
NumberFormat usd = NumberFormat.getCurrencyInstance(Locale.US);
String s = usd.format(1234.5); // "$1,234.50"
Currency yen = Currency.getInstance("JPY");
int frac = yen.getDefaultFractionDigits(); // 0
| Method | Use |
|---|---|
NumberFormat.getCurrencyInstance(loc) | Locale's currency |
fmt.setCurrency(Currency.getInstance("EUR")) | Override |
7. Formatting Dates
| Method | Detail |
|---|---|
DateTimeFormatter.ofLocalizedDate(LONG) | SHORT/MEDIUM/LONG/FULL |
.withLocale(loc) | Apply locale |
8. Using MessageFormat
| Pattern | Meaning |
|---|---|
{0} | Positional arg |
{0,number,currency} | Type + style |
{0,date,short} | Date format |
{0,choice,...} | Plural/conditional |
9. Understanding Default Locale
| Method | Detail |
|---|---|
Locale.getDefault() | JVM default |
Locale.setDefault(loc) | Set globally (caution) |
| Categories | Locale.Category.DISPLAY / FORMAT |
10. Supporting Multiple Languages
| Practice | Detail |
|---|---|
| External strings | Use ResourceBundle (no hardcoded text) |
| Locale-aware compare | Collator.getInstance(loc).compare(a, b) |
| Bidi text | java.text.Bidi for RTL languages |
| Unicode normalization | Normalizer.normalize(s, Form.NFC) |