5.3. Read and set the locale by using the Locale object - Source Code

Code:

package c5.s3;

import java.util.Locale;

/**
 * @author Mikalai Zaikin
 */
public class DefaultLocale {
    public static void main(String... args) {
      Locale l1 = Locale.getDefault();
      System.out.println("Language: " + l1.getLanguage());
      System.out.println("Country: " + l1.getCountry());
      System.out.println("Variant: " + l1.getVariant());
      System.out.println("Display name: " + l1.getDisplayName());
      System.out.println();

      Locale.setDefault(new Locale("es", "ES"));

      l1 = Locale.getDefault();
      System.out.println("Language: " + l1.getLanguage());
      System.out.println("Country: " + l1.getCountry());
      System.out.println("Variant: " + l1.getVariant());
      System.out.println("Display name: " + l1.getDisplayName());
   }
}
					

output:

Language: en
Country: US
Variant:
Display name: English (United States)

Language: es
Country: ES
Variant:
Display name: español (España)
					

Code:

package c5.s3;

import java.text.NumberFormat;
import java.util.Locale;

/**
 * @author Mikalai Zaikin
 */
public class LocaleCreateDemo {
    public static void main(String... args) {

      int i = 14_092_011;

      // Builder
      Locale l1 = new Locale.Builder().setLanguage("fr").setRegion("CA").build();
      System.out.print(l1 + " uses ");
      System.out.println(NumberFormat.getInstance(l1).format(i));

      // Constructor
      Locale l2 = new Locale("fr", "CA");
      System.out.print(l2 + " uses ");
      System.out.println(NumberFormat.getInstance(l2).format(i));

      // Factory method
      Locale l3 = Locale.forLanguageTag("fr-CA");
      System.out.print(l3 + " uses ");
      System.out.println(NumberFormat.getInstance(l3).format(i));

      // Constant
      Locale l4 = Locale.CANADA_FRENCH;
      System.out.print(l4 + " uses ");
      System.out.println(NumberFormat.getInstance(l4).format(i));
   }
}
					

output:

fr_CA uses 14 092 011
fr_CA uses 14 092 011
fr_CA uses 14 092 011
fr_CA uses 14 092 011
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide