Currency getDisplayName(Locale) in Java

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

Syntax:

String java.util.Currency.getDisplayName(Locale locale)

This method takes one argument of type Locale as its parameter. This method gets the name that is suitable for displaying this currency for the specified locale.

Note: If there is no suitable display name found for the specified locale, the ISO 4217 currency code is returned.

Parameters: One parameter is required for this method.

locale: the locale for which a display name for this currency is needed

Returns: the display name of this currency for the specified locale.

Throws:

NullPointerException - if locale is null.

Approach 1: When no exception

Java

import java.util.Currency;
import java.util.Locale;

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

        Currency currency = Currency.getInstance(Locale.US);

        System.out.println(currency.getDisplayName(Locale.UK));

    }
}

Output:

US Dollar


Approach 2: NullPointerException 

Java

import java.util.Currency;
import java.util.Locale;

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

        Currency currency = Currency.getInstance(Locale.US);

        System.out.println(currency.getDisplayName(null));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/sun.util.locale.provider.LocaleServiceProviderPool.getLocalizedObjectImpl(LocaleServiceProviderPool.java:266) at java.base/sun.util.locale.provider.LocaleServiceProviderPool.getLocalizedObject(LocaleServiceProviderPool.java:236) at java.base/java.util.Currency.getDisplayName(Currency.java:641)



No comments:

Post a Comment