Currency.getInstance(String) in Java

Currency.getInstance(String): This method is available in java.util.Currency class of Java.

Syntax:

Currency java.util.Currency.getInstance(String currencyCode)

This method takes one argument of type String as its parameter. This method returns the Currency instance for the given currency code.

Parameters: One parameter is required for this method.

currencyCode: the ISO 4217 code of the currency.

Returns: the Currenc instance for the given currency code.

Throws:

1. NullPointerException - if currencyCode is null.

2. IllegalArgumentException - if currencyCode is not a supported ISO 4217 code.

Approach 1: When no exception

Java

import java.util.Currency;

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

        String currenyCode = "USD";
        System.out.println(Currency.getInstance(currenyCode));

    }
}

Output:

USD


Approach 2: NullPointerException 

Java

import java.util.Currency;

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

        String currenyCode = null;
        System.out.println(Currency.getInstance(currenyCode));

    }
}

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/java.util.Currency.getInstance(Currency.java:305) at java.base/java.util.Currency.getInstance(Currency.java:297)



Approach 3: IllegalArgumentException 

Java

import java.util.Currency;

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

        String currenyCode = "null";
        System.out.println(Currency.getInstance(currenyCode));

    }
}

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