Locale toLanguageTag() Method in Java with Examples

The toLanguageTag() method of Locale class in Java is used to return a well-formed IETF BCP 47 language tag representing this locale object. Now there can be few complications when a language, country or variant does not satisfy the above-mentioned tag which is handled well by this method:

  • If the mentioned language does not satisfy the tag, then it will be emitted as Undetermined or “und”.
  • If the mentioned country does not satisfy the tag, it will be omitted.
  • If the same occurs with the Variant, then each sub-segment is emitted as a subtag.

Syntax:

public String toLanguageTag()

Parameters: This method does not take any parameters.

Return Value: This method returns IETF BCP 47 language tag representation of this locale.

Below programs illustrate the working of toLanguageTag() method:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate
// toLanguageTag() method
  
import java.util.*;
  
public class Locale_Demo {
    public static void main(String[] args)
    {
  
        // Creating a new locale
        Locale first_locale
            = new Locale("Germany");
  
        // Displaying first locale
        System.out.println("Locale: "
                           + first_locale);
  
        // Displaying the LanguageTag
        System.out.println("The LanguageTag: "
                           + first_locale.toLanguageTag());
    }
}

chevron_right


Output:

Locale: germany
The LanguageTag: germany

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate
// toLanguageTag() method
  
import java.util.*;
  
public class Locale_Demo {
    public static void main(String[] args)
    {
  
        // Creating a new locale
        Locale first_locale
            = new Locale("en", "USA");
  
        // Displaying first locale
        System.out.println("Locale: "
                           + first_locale);
  
        // Displaying the LanguageTag
        System.out.println("The LanguageTag: "
                           + first_locale.toLanguageTag());
    }
}

chevron_right


Output:

Locale: en_USA
The LanguageTag: en

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#toLanguageTag()



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.