Getting Current Locale in Java

Learn to get the locale of the user in Java that is used to format the content according to the user’s demographics (geographical, political, or cultural information).

1. What is Locale?

Suppose we are developing an application and we are asked to make the application customized for international end-users. To customize our application for the international audience, we will need to know the location of a user and then format certain location-specific information (such as date-time, currency, field labels etc) based on the location information.

The location information in Java is represented by the Locale class. We can use this class locale-sensitive operations such as displaying a number, amount and so on.

The Locale class implements IETF BCP 47 that provides the standardized code or tag used to identify human languages on the Internet.

2. Get User Locale in Web Applications

In Java web applications, locale information is retrieved from ServletRequest ( and HttpServletRequest ) object obtained on the server-side. Use the below method call for getting the current locale information:

Locale currentLocale = httpServletRequest.getLocale();

System.out.println(currentLocale.getDisplayLanguage()); //English
System.out.println(currentLocale.getDisplayCountry());	//United States

System.out.println(currentLocale.getLanguage());		//en
System.out.println(currentLocale.getCountry());			//US

3. Get Default Locale in Desktop Applications

In Java desktop applications, locale information is retrieved using Locale.getDefault() that returns the default locale set in the Java Virtual Machine. We can also use system properties "user.country" and "user.language" for this information.

The Java Virtual Machine sets the default locale during startup based on the host machine environment and preferences.

Locale currentLocale = Locale.getDefault();

System.out.println(currentLocale.getDisplayLanguage());  //English
System.out.println(currentLocale.getDisplayCountry());	//United States

System.out.println(currentLocale.getLanguage()); //en
System.out.println(currentLocale.getCountry());  //US

System.out.println(System.getProperty("user.language"));  //en
System.out.println(System.getProperty("user.country"));  //US

That’s all regarding this simple, easy but important information regarding getting locale information in java.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.