Skip to content
Advertisement

Locale.setDefault affecting Locale.getDefault.getCountry

The output of the following code

Locale.setDefault(new Locale("fr"));
System.out.println("Start");
System.out.println(Locale.getDefault().getCountry());
System.out.println("End");

is

Start

End

whereas the output of this code

//Locale.setDefault(new Locale("fr"));
System.out.println("Start");
System.out.println(Locale.getDefault().getCountry());
System.out.println("End");

is

Start
US
End

I’m curious why the output of the first code block which changes the default language setting to French results in an empty string being produced as the output for Locale.getDefault().getCountry()

Advertisement

Answer

According to documentation:

A java.util.Locale is a lightweight object that contains only a few important members:

  • A language code
  • An optional country or region code
  • An optional variant code

When you create instance of class Locale with your constructor, you create a locale with french language and without country or variant specified.

Next you pass Locale you had created to setDefault method. So since then you have default locale with french language and no country or variant.

Locale.setDefault does not allow you to set only default language. You always set whole Locale object.

To solve your problem you can first get country code from default locale and then create Locale with French language and default country:

String defaultCountryCode = Locale.getDefault().getCountry();
Locale.setDefault(new Locale("fr", defaultCountryCode));
System.out.println("Start");
System.out.println(Locale.getDefault().getCountry());
System.out.println("End");

and you will get

Start
US
End
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement