Java Currency getInstance()

In this guide, you will learn about the Currency getInstance() method in Java programming and how to use it with an example.

1. Currency getInstance() Method Overview

Definition:

The getInstance() method of the Currency class in Java is a static method used to obtain a Currency instance representing the specified currency code or Locale

The method throws IllegalArgumentException if the currency code is not a supported ISO 4217 code or the specified Locale doesn’t have a country.

Syntax:

1. public static Currency getInstance(String currencyCode)
2. public static Currency getInstance(Locale locale)

Parameters:

- currencyCode: a String representing the desired currency.

- locale: the locale for which a Currency instance is needed.

Key Points:

- The Currency class is part of the java.util package.

- The getInstance() method comes in two overloaded forms; one takes a string representing the currency code, and the other takes a Locale object.

- The method returns a Currency instance.

- An IllegalArgumentException is thrown if the currency code is invalid or the Locale doesn’t have a country.

2. Currency getInstance() Method Example

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

public class CurrencyGetInstanceExample {
    public static void main(String[] args) {
        // Getting Currency instance using currency code
        Currency usdCurrency = Currency.getInstance("USD");
        System.out.println("Currency Code: " + usdCurrency.getCurrencyCode());

        // Getting Currency instance using Locale
        Locale japanLocale = Locale.JAPAN; // Locale for Japan
        Currency jpyCurrency = Currency.getInstance(japanLocale);
        System.out.println("Currency Code for Japan: " + jpyCurrency.getCurrencyCode());

        // Attempting to get Currency instance using an invalid currency code
        try {
            Currency invalidCurrency = Currency.getInstance("INVALID");
        } catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException: " + e.getMessage());
        }
    }
}

Output:

Currency Code: USD
Currency Code for Japan: JPY
IllegalArgumentException: Invalid ISO 4217 currency code INVALID

Explanation:

In this example, we first used the getInstance() method with a currency code ("USD") to obtain a Currency instance for the US Dollar and printed its currency code. 

Next, we created a Locale instance for Japan and used it to obtain a Currency instance for Japanese Yen, printing its currency code. Finally, we tried obtaining a Currency instance using an invalid currency code, which resulted in an IllegalArgumentException.

Comments