[go: up one dir, main page]

Core Java

Java Currency Code Symbol Mapping Example

In financial applications, e-commerce platforms, or internationalization (i18n) support, you often need to convert a currency code (like "USD", "EUR", "JPY") into its corresponding currency symbol ("$", "€", "¥"). Java provides built-in support for currency-related operations via the java.util.Currency and java.util.Locale classes. This article explores how to map currency codes to their symbols using these APIs.

1. Mapping Currency Code to Symbol Using Currency.getSymbol()

Java’s Currency class provides a getSymbol() method that returns the symbol for a given currency code, based on a specified locale.

public class CurrencySymbolExample {

    public static void main(String[] args) {
        printCurrencySymbol("USD", Locale.US);
        printCurrencySymbol("EUR", Locale.GERMANY);
        printCurrencySymbol("JPY", Locale.JAPAN);
        printCurrencySymbol("INR", Locale.forLanguageTag("en-IN")); // India
        printCurrencySymbol("NGN", Locale.forLanguageTag("en-NG")); // Nigeria
        printCurrencySymbol("GBP", Locale.UK);
    }

    private static void printCurrencySymbol(String currencyCode, Locale locale) {
        Currency currency = Currency.getInstance(currencyCode);
        String symbol = currency.getSymbol(locale);
        System.out.println("Currency Code: " + currencyCode + ", Symbol: " + symbol);
    }
}

This Java program defines a printCurrencySymbol method that uses Currency.getInstance(currencyCode) to get the Currency object for the given currency code, and then retrieves the symbol using currency.getSymbol(locale).

The main method calls the printCurrencySymbol method for different currency codes (such as USD, EUR, JPY, INR, NGN, and GBP) along with corresponding locales (e.g., Locale.US, Locale.GERMANY, Locale.JAPAN, Locale.forLanguageTag("en-IN"), Locale.forLanguageTag("en-NG"), and Locale.UK). It then prints the currency code along with its symbol to the console, providing localized currency symbols based on the locale provided.

Output:

Output of Java Currency Code to Symbol Mapping

2. Mapping All ISO Currency Codes to Symbols

We can iterate through all available currency codes using Currency.getAvailableCurrencies() and map them to their symbols for a given default locale.

public class AllCurrencySymbols {

    public static void main(String[] args) {
        Locale defaultLocale = Locale.US;
        Set<Currency> currencies = Currency.getAvailableCurrencies();

        for (Currency currency : currencies) {
            String code = currency.getCurrencyCode();
            String symbol = currency.getSymbol(defaultLocale);
            System.out.println(code + " -> " + symbol);
        }
    }
}

Here, we retrieve all currencies using Currency.getAvailableCurrencies(). For each currency, we print the ISO code and its symbol for the US locale. Some symbols like A$ and CA$ show that Java adds a country code in front to tell apart currencies that use the same symbol.

Sample Output (truncated)

USD -> $
EUR -> €
JPY -> ¥
KRW -> ₩
GBP -> £
INR -> ₹
AUD -> A$
CAD -> CA$
...

3. Using a Hardcoded Map (Custom Mapping)

Sometimes, relying on Java’s built-in locale and currency support might not give the exact symbol we want, especially for currencies that share similar symbols or when we need to show a specific format. In such cases, we can create our own hardcoded map that links currency codes directly to their symbols. This approach gives us full control over how each symbol is displayed, making it useful for custom formatting or when working with unsupported locales.

public class HardcodedCurrencyMap {

    private static final Map currencySymbolMap = new HashMap();

    static {
        currencySymbolMap.put("USD", "$");
        currencySymbolMap.put("EUR", "€");
        currencySymbolMap.put("JPY", "¥");
        currencySymbolMap.put("GBP", "£");
        currencySymbolMap.put("INR", "₹");
        currencySymbolMap.put("CNY", "¥");
        currencySymbolMap.put("AUD", "A$");
        currencySymbolMap.put("CAD", "CA$");
        currencySymbolMap.put("NGN", "₦");
    }

    public static void main(String[] args) {
        printSymbol("USD");
        printSymbol("EUR");
        printSymbol("INR");
        printSymbol("XYZ"); // Unknown
        printSymbol("NGN");
        printSymbol("ABC"); // Unknown
        printSymbol("CAD");
    }

    private static void printSymbol(String code) {
        String symbol = currencySymbolMap.getOrDefault(code, "[Unknown]");
        System.out.println(code + " -> " + symbol);
    }
}

This Java class, HardcodedCurrencyMap, demonstrates how to manually map currency codes to their corresponding symbols using a hardcoded HashMap. The static map currencySymbolMap is initialized with common currency codes like USD, EUR, JPY and INR each associated with its respective symbol. For example, "USD" maps to "$", "INR" maps to "₹". Some entries, like "AUD" and "CAD", use prefixed symbols ("A$", "CA$") to disambiguate them from other dollar-based currencies.

The main method calls the printSymbol method multiple times to retrieve and print the symbol for each currency code. If the currency code exists in the map, its symbol is displayed. If not, a default value of "[Unknown]" is returned and printed instead. For instance, "XYZ" and "ABC" are not part of the map, so the output for them is "XYZ -> [Unknown]" and "ABC -> [Unknown]".

This approach is fast, customizable, and ideal for small-scale applications. We completely control the output and can even override the default behavior. However, it is not scalable and requires manual updates when supporting new currencies.

Output

USD -> $
EUR -> €
INR -> ₹
XYZ -> [Unknown]
NGN -> ₦
ABC -> [Unknown]
CAD -> CA$

4. Conclusion

In this article, we explored various approaches to mapping currency codes to currency symbols in Java. We began by using the built-in Currency and Locale classes to retrieve localized currency symbols, which work well for most standard use cases. We then introduced a custom solution using a hardcoded Map to manually define currency code-to-symbol relationships, offering greater control and flexibility.

5. Download the Source Code

This article explored how to perform currency code to symbol mapping in Java.

Download
You can download the full source code of this example here: java currency code symbol mapping

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button