Locale class

In this chapter you will learn:

  1. Locale class
  2. How to use Locale to set date format for a country
  3. Sets the default locale for this instance of the Java Virtual Machine

Locale class

The Locale class describes a geographical or cultural region. The Locale class defines the following constants that are useful for dealing with the most common locales:

  • CANADA
  • CANADA_FRENCH
  • CHINA
  • CHINESE
  • ENGLISH
  • FRANCE
  • FRENCH
  • GERMAN
  • GERMANY
  • ITALIAN
  • ITALY
  • JAPAN
  • JAPANESE
  • KOREA
  • KOREAN
  • PRC
  • SIMPLIFIED_CHINESE
  • TAIWAN
  • TRADITIONAL_CHINESE
  • UK
  • US

For example, the expression Locale.CANADA represents the Locale object for Canada.

The constructors for Locale are

Locale(String language) 
Locale(String language, String country) 
Locale(String language, String country, String data)

These constructors build a Locale object to represent a specific language and in the case of the last two, country. These values must contain ISO-standard language and country codes.

The default locale can be obtained using getDefault( ), shown here:

static Locale getDefault( )

The following code get the default locale and output its information.

import java.util.Locale;
//from j  a  va 2  s. c  om
public class Main {

  public static void main(String[] av) {
    Locale l = Locale.getDefault();
    System.out.println("Today's Locale is " + l);
  }
}

The code above generates the following result.

Use Locale to set the date format for a country

DateFormat and SimpleDateFormat depend on the locale. The following code shows how to bind Locale.GERMANY to NumberFormat.

import java.text.NumberFormat;
import java.util.Locale;
/*  j  ava2 s. c  o  m*/
public class MainClass {
  public static void main(String args[]) throws Exception {
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setParseIntegerOnly(false);
    double usersNumber = 1976.0826;

    numberFormat = NumberFormat.getNumberInstance(Locale.GERMANY);
    System.out.println("User's number (GERMANY): " + numberFormat.format(usersNumber));
    
  }
}

The code above generates the following result.

Sets the default locale for this instance of the Java Virtual Machine

static void setDefault(Locale newLocale) Sets the default locale for this instance of the Java Virtual Machine.

import java.util.Locale;
//  j  a v  a 2 s  .c o  m
public class Main {
  public static void main(String[] argv) throws Exception {

    Locale.setDefault(Locale.FRENCH);

  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to get country name and language name for a Locale
  2. How to get the ISO country codes
  3. How to get 2-letter language codes defined in ISO 639
Home » Java Tutorial » Internationalization
Locale class
Locale country name and language name
ResourceBundle
Currency class