Home » Java programming language

Java Currency getInstance() Method with Example

Currency Class getInstance() method: Here, we are going to learn about the getInstance() method of Currency Class with its syntax and example.
Submitted by Preeti Jain, on February 12, 2020

Currency Class getInstance() method

Syntax:

    public static Currency getInstance(Locale lo);
    public static Currency getInstance(String curr_code);
  • getInstance() method is available in java.util package.
  • getInstance(Locale lo) method is used to get the Currency instance for the specified Locale (lo).
  • getInstance(String curr_code) method is used to get the Currency instance for the specified Currency code (curr_code).
  • These methods may throw an exception at the time of returning Currency instance.
    • NullPointerException: This exception may throw when the given parameter is null exists.
    • IllegalArgumentException: This exception may throw when ISO 3166 un-support the given parameter.
  • These are static methods, it is accessible with the class name and if we try to access these methods with the class object then also we will not get an error.

Parameter(s):

  • In the first case, getInstance(Locale lo),
    • Locale lo – represents the locale for whose Currency instance is needed.
  • In the second case, getInstance(String curr_code)
    • String curr_code – represent the currency code (curr_code).

Return value:

In both the cases, the return type of the method is Currency,

  • getInstance(Locale lo) – returns Currency instance for the given locale (lo).
  • getInstance(String curr_code) – returns Currency instance for the given currency code (curr_code).

Example:

// Java program is to demonstrate the example of
// getInstance() method of Currency

import java.util.*;

public class GetInstanceOfCurrency {
    public static void main(String args[]) {
        // Instantiates a currency with INR code
        Currency c1 = Currency.getInstance("INR");

        // Instantiates a currency for the given locale
        Locale lo = Locale.US;
        Currency c2 = Currency.getInstance(lo);

        // By using getInstance(c1) method is to return
        // the Currency instance for the given currency code
        System.out.print("c1.getCurrencyCode(): ");
        System.out.println(c1.getCurrencyCode());

        // By using getSymbol(lo) method is to return
        // the Currency instance for the given locale
        System.out.print("c2.getCurrencyCode(): ");
        System.out.println(c2.getCurrencyCode());
    }
}

Output

c1.getCurrencyCode(): INR
c2.getCurrencyCode(): USD



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.