1

How to get the language code based on country code in java
Hi
I had a situation where I need to find the language based on country code.
For country name "switzerland" I had country code as "CH" .
But there can be 3 languges like German,french and ukenglish in Switzerland . I need to find the language code based on country code.
Scenario : My country code is "CH" . I need to get the language code based on this country code.

Thanks in advance

Razib
  • 10,965
  • 11
  • 53
  • 80
  • `there can be 3 languges like German, French and` ... **Italian** (Suisse-Italian), not UK English! Well, they are all Switzerland variants of German, French and Italian. – Phantômaxx Mar 28 '15 at 20:16
  • 4
    So which of the three languages of Switzerland do you expect get? If not all three, it's not clear what you want. There's no "the" language code for Switzerland. – alexis Mar 28 '15 at 20:24
  • How to fetch the German language code for switzerland country code in java ? – Android_programmer_office Mar 28 '15 at 20:36
  • 2
    If you already know you want German, rather than either of the other, equally official, languages, why not just use "de"? Or use `new Locale("ch", "de")` to create a Locale object for the combination of Switzerland and German. – Patricia Shanahan Mar 28 '15 at 22:01
  • iam also looking for answer. Have you got any solution for this – aj0822ArpitJoshi Oct 15 '19 at 06:45

2 Answers2

7

This program prints the language codes for all available locales for Switzerland. It can easily be modified to e.g. return a List<String> of language codes. Picking the one you want is left as an exercise for the reader - the Swiss have not chosen to pick a single preferred language for their country.

import java.util.Locale;

public class Test {
  public static void main(String[] args) {
    Locale[] all = Locale.getAvailableLocales();
    for (Locale locale : all) {
      String country = locale.getCountry();
      if(country.equalsIgnoreCase("CH")){
        System.out.println(locale.getLanguage());
      }
    }
  }
}

Output:

fr
de
it
Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
  • 1
    BTW: if you need the country's name in a specific locale's language: https://www.mkyong.com/java/display-a-list-of-countries-in-java/ – Kawu Dec 30 '19 at 16:40
0

You can use following constructor of Locale -

   Locale(String language, String country)

For USA (code: US) the language is English (code "en"). So you can do this -

Locale locale = new Locale("en", "US");
Razib
  • 10,965
  • 11
  • 53
  • 80
  • Can I use like below : Locale locale = new Locale("CH"); String language = locale.getDisplayLanguage(). is it correct ? – Android_programmer_office Mar 28 '15 at 20:22
  • 3
    This answer is pretty unrelated to the question. @Android_programmer_office: no this is not correct. In fact, you cannot dereference a language from a country code directly. See Patricia's answer for further information. – itchee Mar 28 '15 at 21:06