Currency.getInstance(Locale): This method is available in java.util.Currency class of Java.
Syntax:
Currency java.util.Currency.getInstance(Locale locale)
This method takes one argument of type Locale as its parameter. This method returns the Currency instance for the country of the given locale. The language and variant components of the locale are ignored.
Note: The result may vary over time, as countries change their currencies.
Parameters: One parameter is required for this method.
locale: the locale for whose country a Currency instance is needed.
Returns: the Currency instance for the country of the given locale, or null.
Throws:
1. NullPointerException - if the locale is null.
2. IllegalArgumentException - if the country of the given locale is not a supported ISO 3166 country code.
Approach 1: When no exception
Java
import java.util.Currency;import java.util.Locale;public class CurrencygetInstance {public static void main(String[] args) {System.out.println(Currency.getInstance(Locale.US));}}
Output:
USD
Approach 2: NullPointerException
Java
import java.util.Currency;import java.util.Locale;public class CurrencygetInstance {public static void main(String[] args) {Locale locale = null;System.out.println(Currency.getInstance(locale));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Locale.getUnicodeLocaleType(String)" because "locale" is null at java.base/java.util.Currency.getInstance(Currency.java:382)
Approach 2: IllegalArgumentException
Java
import java.util.Currency;public class CurrencygetInstance {public static void main(String[] args) {System.out.println(Currency.getInstance("null"));}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException at java.base/java.util.Currency.getInstance(Currency.java:316) at java.base/java.util.Currency.getInstance(Currency.java:297)
No comments:
Post a Comment