Locale getDisplayName() inLocale in Java

getDisplayName(): This method is available in java.util.Locale class of Java.

Syntax:

String java.util.Locale.getDisplayName(Locale inLocale)

This method takes one argument of type Locale as its parameter. This method returns a name for the locale that is appropriate for display to the user. 

Note: If the language, script, country, and variant fields are all empty, this function returns the empty string.

Parameters: One parameter is required for this method.

inLocale: The locale for which to retrieve the display name.

Returns: The name of the locale appropriate to display.

Throws: NullPointerException - if inLocale is null.

For Example:

Locale locale = new Locale("en", "USA")

Locale inLocale = new Locale("fr", "FR")

locale.getDisplayName(inLocale) = > It returns anglais (USA).

Approach 1: When inLocale is not null.

Java

import java.util.Locale;

public class LocalegetDisplayName2 {
    public static void main(String[] args) {

        Locale locale = new Locale("en""USA");

        Locale inLocale = new Locale("fr""FR");

        System.out.println(locale.getDisplayName(inLocale));
    }
}

Output:

anglais (USA)


Approach 2: When inLocale is null.

Java

import java.util.Locale;

public class LocalegetDisplayName2 {
    public static void main(String[] args) {

        Locale locale = new Locale("en""USA");

        Locale inLocale = null;

        System.out.println(locale.getDisplayName(inLocale));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "Object.hashCode()" because "key" is null at java.base/java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936) at java.base/sun.util.locale.provider.JRELocaleProviderAdapter.getLocaleResources(JRELocaleProviderAdapter.java:387) at java.base/java.util.Locale.getDisplayName(Locale.java:2022)


No comments:

Post a Comment