Locale

java.util.Locale Example

In this article we will discuss about the Locale class from java.util package. The Locale is used to make the system relevant and usable for the users from different cultures. In other words, it is used to customize the system for different people of different region, culture and language.

A Locale object represents a specific geographical, political, or cultural region.

Let’s discuss about the Locale class and how to create, query and use a Locale object.

 

1. Locale Instantiation

There are many ways to create a Locale object. As of JDK 7, there are four ways to create a Locale object. In the following example, we will see different ways of creating it and differences between them.

1.1 Using constructor

1.1a. Locale(String language): Construct a locale from a language code. For e.g. “fr” is a language code for French.

1.1.b. Locale(String language, String country): When you have a language code and a country, you can use this constructor with two parameters that takes a language as first parameter and a country as second parameter to create a locale object.

1.1c. Locale(String language, String country, String variant): Construct a locale from language, country and variant. Any arbitrary value can be used to indicate a variation of a Locale.

1.2 Using Builder method

From JDK 7 releases, the Locale provides a Builder to create an instance of the Locale class. Using Locale.Builder you can instantiate an object that conforms to BCP 47 syntax.

Locale localeFromBuilder = new Locale.Builder().setLanguage("en").setRegion("GB").build();

1.3 Using forLanguageTag method:

forLanguageTag (String languageTag) returns a locale for the specified IETF BCP 47 language tag string. If the specified language tag contains any ill-formed subtags, the first such subtag and all the following subtags are ignored.

Locale forLangLocale = Locale.forLanguageTag("en-GB");

1.4 Locale constants

Java provides a set of pre-defined constants for some languages and countries. If a language constant is specified, then the regional portion of that locale is undefined.

Locale localeCosnt = Locale.FRANCE;

LocaleExample.java

package com.javacodegeeks.corejava.util;

import java.util.Locale;

public class LocaleExample {

	public static void main(String[] args) {
		
		// Creates a locale object using one parameter to constructor
		Locale locale = new Locale("fr");	
		System.out.println("locale: "+locale);
		
		// Create a locale object using two parameters constructor
		Locale locale2 = new Locale("fr", "CANADA");
		System.out.println("locale2: "+locale2);
		
		// Create a locale object using three parameters constructor
		Locale locale3 = new Locale("no", "NORWAY", "NY");
		System.out.println("locale3: "+locale3);
		
		// A local object from Locale.Builder
		Locale localeFromBuilder = new Locale.Builder().setLanguage("en").setRegion("GB").build();
		System.out.println("localeFromBuilder: "+localeFromBuilder);
		
		//Locale from forLanguageTag method
		Locale forLangLocale = Locale.forLanguageTag("en-GB");
		System.out.println("forLangLocale: "+forLangLocale);
		
		//Using Locale Contant
		Locale localeCosnt = Locale.FRANCE;
		System.out.println("localeCosnt: "+localeCosnt);
	}
}

  • If we run the above code, we will have the following results:
locale: fr
locale2: fr_CANADA
locale3: no_NORWAY_NY
localeFromBuilder: en_GB
forLangLocale: en_GB
localeCosnt: fr_FR

Although, you can use any of these ways to create a locale object. But it is recommended to use forLanguageTag and Locale.Builder methods. The reason is these two methods return a locale for the specified IETF BCP 47 language tag string. BCP 47 imposes syntax restrictions that are not imposed by Locale’s constructors. This means that conversions between some Locales and BCP 47 language tags cannot be made without losing information.

2. Methods

In this section, we will discuss about some of the important methods of the Locale class. You can use these methods on a locale object to get some information about the Locale.

LocaleMethodExample.java

package com.javacodegeeks.corejava.util;

import java.util.Locale;

public class LocaleMethodExample {

	public static void main(String[] args) {
		
		// Getting a default locale object
		Locale locale = Locale.getDefault();
		System.out.println("Default Locale: "+locale);
		
		// Getting all available locales from current instance of the JVM
		Locale []availableLocale = Locale.getAvailableLocales();
		for(Locale aLocale : availableLocale){
			System.out.println("Name of Locale: "+aLocale.getDisplayName());
			System.out.println("Language Code: "+aLocale.getLanguage()+", Language Display Name: "+aLocale.getDisplayLanguage());
			System.out.println("Country Code: "+aLocale.getCountry()+", Country Display Name: "+aLocale.getDisplayCountry());
			if(!aLocale.getScript().equals("")){
				System.out.println("Script Code: "+aLocale.getScript()+", Script Display Name: "+aLocale.getDisplayScript());
			}
			if(!aLocale.getVariant().equals("")){
				System.out.println("Variant Code: "+aLocale.getVariant()+", Variant Display Name: "+aLocale.getDisplayVariant());
			}
			System.out.println("****************************************************************");
		}
	}

}

  • If we run the above code, we will have the following results:
Default Locale: en_US
Name of Locale: Malay (Malaysia)
Language Code: ms, Language Display Name: Malay
Country Code: MY, Country Display Name: Malaysia
****************************************************************
Name of Locale: Arabic (Qatar)
Language Code: ar, Language Display Name: Arabic
Country Code: QA, Country Display Name: Qatar
****************************************************************
Name of Locale: Icelandic (Iceland)
Language Code: is, Language Display Name: Icelandic
Country Code: IS, Country Display Name: Iceland
****************************************************************
Name of Locale: Serbian (Latin,Montenegro)
Language Code: sr, Language Display Name: Serbian
Country Code: ME, Country Display Name: Montenegro
Script Code: Latn, Script Display Name: Latin
****************************************************************
Name of Locale: Thai (Thailand,TH)
Language Code: th, Language Display Name: Thai
Country Code: TH, Country Display Name: Thailand
Variant Code: TH, Variant Display Name: TH
****************************************************************
.......[output truncated]

Please note that in the above example, we have printed only that script and variant which are specified for the locale object.

Locale.getDefault() gets the current value of the default locale for current instance of the Java Virtual Machine. The Java Virtual Machine sets the default locale during startup based on the host environment.

Locale.getAvailableLocales() returns an array of all available locales installed on that particular JVM machine.

String getDisplayName() is an instance method which returns the name of the locale object (appropriate to display) in string form. The name contains values returned by getDisplayLanguage(), getDisplayScript(),getDisplayCountry(), and getDisplayVariant() methods .

String getLanguage() returns the language code of the locale object.

String getDisplayLanguage() returns the name of the locale’s language. It shows an appropriate name for display to the user.

String getCountry() returns the country/region code for this locale, which should either be the empty string, an uppercase ISO 3166 2-letter code, or a UN M.49 3-digit code.

String getDisplayCountry() returns the name of the locale’s country. It shows an appropriate name for display to the user.

String getScript() returns the script code for this locale. It should either be the empty string or an ISO 15924 4-letter script code. The first letter is uppercase and the rest are lowercase, for example, ‘Latn’, ‘Cyrl’.

String getDisplayScript() returns the name of the locale’s script appropriate for display to the user.

String getVariant() returns the variant code, or the empty string if none is defined.

String getDisplayVariant() returns a name for the locale’s variant code that is appropriate for display to the user.

3. Locale sensitive classes

The Locale is the mechanism for identifying the kind of object that you would like to get. Java provides certain classes which provide locale specific operations. For example, they provide methods to format values that represent dates, currency and numbers according to a specific locale. These classes are known as Locale sensitive classes.

In the following example, we will use NumberFormat, Currency, and DateFormat classes to illustrate about locale sensitive operations.

LocaleSensitiveExample.java


package com.javacodegeeks.corejava.util;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;

public class LocaleSensitiveExample {

	public static void main(String[] args) {

		long number = 5000000L;
		
		NumberFormat numberFormatDefault = NumberFormat.getInstance();
		System.out.println("Number Format using Default Locale: "+numberFormatDefault.format(number));
		
		NumberFormat numberFormatLocale = NumberFormat.getInstance(Locale.ITALY);
		System.out.println("Number Format using ITALY Locale: "+numberFormatLocale.format(number));
		
		NumberFormat numberFormatDefaultCurrency = NumberFormat.getCurrencyInstance();
		System.out.println("Currency Format using Default Locale: "+numberFormatDefaultCurrency.format(number));
		
		NumberFormat numberFormatLocaleCurrency = NumberFormat.getCurrencyInstance(Locale.ITALY);
		System.out.println("Currency Format using ITALY Locale: "+numberFormatLocaleCurrency.format(number));
		
		Currency currency = Currency.getInstance(Locale.CHINA);
		System.out.println(currency.getDisplayName()+" ("+currency.getCurrencyCode()+") "+currency.getDisplayName());
		
		Date currentDate = new Date();
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.GERMAN);
		System.out.println("Date Format in German Locale: "+dateFormat.format(currentDate));
	}

}

  • If we run the above code, we will have the following results:

Number Format using Default Locale: 5,000,000
Number Format using ITALY Locale: 5.000.000
Currency Format using Default Locale: $5,000,000.00
Currency Format using ITALY Locale: € 5.000.000,00
Chinese Yuan (CNY) Chinese Yuan
Date Format in German Locale: Samstag, 31. Mai 2014

In the above example, we have used the getInstance() static method to get the instance about the respective class. The getInstance() methods used in two variety one without locale (which uses the default locale set in the current instance of the JVM) and another with a Locale as its parameter.

You can clearly see the differences in the output due to difference in the locale object used.

This was an example of how to use the Locale class and some of its basic methods.

4. Download the source code

You can download the source code of this example from here: LocaleExample.zip

Rohit Joshi

Rohit Joshi works as a Software Engineer in the Consumer Product Sector. He is a Sun Certified Java Programmer. He had worked in projects related to different domains. He is also involved in system analysis and system designing. He mainly works in Core Java and J2EE technologies but also have good experience in front-end technologies like Javascript and Jquery.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
shreya
shreya
6 years ago

Hi, NIce article.
I am looking for somethin like: IF I enter some text then it should change the text from one langue to another .For exmaple, “Hello” is in english , I want the same in Chineese.
Is that possible .I was looking for string formater class.

Back to top button