Locale.forLanguageTag() vs new Locale()

Viewed 76

Which one to use?

final Locale locale = Locale.forLanguageTag("en-US");

or

final Locale locale = new Locale("en", "US");

Both of them have tons of code when you look at their implementations and I cannot see from this code which one is faster or should be preferred.

As I use it for every single request to my web application, it would be nice to know which one is more suitable for my case.

1 Answers

Constants

Locale class provides a number of constants for frequently used locales: Locale.CANADA, Locale.CANADA_FRENCH, Locale.CHINA, Locale.UK, etc.

Instead of creating a new instance of locale for English as a language and US as a country via new Locale("en", "US") it's preferable to use static field Locale.US.

Locale constructors

There are three overloaded constructors which allow you to create a Local object from language, country and variant.

If you're enough with this information, go with a constructor.

Note: constructor call always creates a new object in memory.

Locale.forLanguageTag

Static method Locale#forLanguageTag() allows to construct an instance of Locale by providing IETF BCP 47 language tag (also see RFC 4647 "Matching of Language Tags" and RFC 5646 "Tags for Identifying Languages").

Withing a language tag apart from the language and country you can specify various details like calendar, numeric system, currency.

Note: forLanguageTag() (as well as Local.Builder) after parsing is complete, provides an instance from the Cache (if already exists).

Example:

Locale buddhistCal = Locale.forLanguageTag("en-EN-u-ca-buddhist");
Locale arabicNum = Locale.forLanguageTag("en-EN-u-nu-arab");
Locale thaiNum = Locale.forLanguageTag("en-EN-u-nu-thai");
        
LocalDate date = LocalDate.now();
    
System.out.println(date);
System.out.println(date.format(DateTimeFormatter.ISO_DATE.localizedBy(buddhistCal)));
System.out.println(date.format(DateTimeFormatter.ISO_DATE.localizedBy(arabicNum)));
System.out.println(date.format(DateTimeFormatter.ISO_DATE.localizedBy(thaiNum)));

Output:

2022-09-07
2565-09-07     // buddhist calendar
٢٠٢٢-٠٩-٠٧     // arabic numbers
๒๐๒๒-๐๙-๐๗    // thai numbers
Related