java.util.Currency methods with example

Currency is a pre-defined class present in the util package of Java. ISO 4217 is an internationally accepted standard. It recognizes currency and its code from all over the world. So, let us see some of the java.util.Currency methods.

java.util.Currency methods

  • Currency.getInstance(): This method creates an instance of the input currency code. Therefore, I will create an instance for the input currency.
Currency c = Currency.getInstance("USD");

Input parameter:

ISO 4217 currency code.

Output:

Returns instance of the country currency code.
  • getCurrencyCode(): With the help of instance created, I can get the currency code.
String code = c.getCurrencyCode();

Input:
Use method with currency instance.

Output:

USD
  • getDefaultFractionDigits():  If I use this method, it will return me the number of fraction digits of the current instance.
int fd = c.getDefaultFractionDigits();

Input:

Use method with currency instance.

Output:

2
  • getDisplayName(): I can get the complete name of the currency. I will do that using the currency code argument. As a result, I will obtain the currency name in my string variable.
String dname = c.getDisplayName();

Input:

Call method with the help of instance created at the start.

Output:
US Dollar
  • getSymbol(): With the help of this method, I can obtain the currency symbol. I will use the same currency instance created. As a result, the currency symbol will be returned.
String symbol = c.getSymbol();

Input:

Using the instance created, call the method.

Output:
$


 

I have shown the code below:

import java.util.*; 
public class currency1 
{ 
    public static void main(String[] args) 
    { 
        // make instance of 'USD'  
        Currency c = Currency.getInstance("USD"); 
        
        // get ISO 4217 code of instance created 
        String code = c.getCurrencyCode(); 
        System.out.println("US Dollar code : " + code);  
        System.out.println(" "); 
  
        // get fraction digits of the currency 
        int fd = c.getDefaultFractionDigits(); 
        System.out.println("USD Fraction digits : " + fd);  
        System.out.println(" "); 
  
        // get display name of the currency
        String dname = c.getDisplayName();
        System.out.println("USD Display : " + dname); 
        System.out.println(" "); 
  
        // get symbol of currency
        String symbol =  c.getSymbol();
        System.out.println("USD Symbol : " + symbol); 
  
    } 
}

Output:

US Dollar cod:        USD

USD Fraction digits:  2

USD Display:          US Dollar

USD Symbol:           $

Leave a Reply

Your email address will not be published. Required fields are marked *