Wednesday, 13 November 2013

Get Currency Symbol by Country in Java

The following example illustrates getting currency symbol or code by country code in Java. This tiny program, which is not more than 2 lines, does the thing. In this example, you'll learn:
  1. How to create a Locale object by language and country name?
  2. How to create a Currency object from Locale object?
  3. How to get symbol of a currency?

import java.util.*;
class GetCurrencySymbol
{
    public static void main(String args[])
    {
    Currency c=Currency.getInstance(new Locale("en",args[0]));
    System.out.println("Symbol is "+c.getSymbol());
    }
}

new Locale("en",args[0]); This constructor takes language and country code as parameter and creates Locale object.
Currency.getInstance(): This method takes java.util.Locale object and returns a Currency object. This is a factory method.
getSymbol(): This method gets the symbol of the currency associated with the object.

No comments:

Post a Comment