Introduction
The Currency
class in Java, part of the java.util
package, represents currency information, including currency codes, symbols, and default fractional digits.
Table of Contents
- What is the
Currency
Class? - Common Methods
- Examples of Using the
Currency
Class - Conclusion
1. What is the Currency Class?
The Currency
class provides a representation of currency, allowing you to get currency details such as the currency code and symbol. It is useful for financial applications that need to display or process monetary values.
2. Common Methods
getInstance(String currencyCode)
: Returns theCurrency
instance for the specified currency code.getInstance(Locale locale)
: Returns theCurrency
instance for the specified locale.getCurrencyCode()
: Returns the ISO 4217 currency code of the currency.getSymbol()
: Returns the symbol of the currency for the default locale.getSymbol(Locale locale)
: Returns the symbol of the currency for the specified locale.getDefaultFractionDigits()
: Returns the number of fractional digits used by the currency.
3. Examples of Using the Currency Class
Example 1: Getting Currency by Code
This example demonstrates how to get a Currency
instance using a currency code.
import java.util.Currency;
public class CurrencyCodeExample {
public static void main(String[] args) {
Currency currency = Currency.getInstance("USD");
System.out.println("Currency Code: " + currency.getCurrencyCode());
System.out.println("Currency Symbol: " + currency.getSymbol());
System.out.println("Fraction Digits: " + currency.getDefaultFractionDigits());
}
}
Output:
Currency Code: USD
Currency Symbol: $
Fraction Digits: 2
Example 2: Getting Currency by Locale
This example shows how to get a Currency
instance using a locale.
import java.util.Currency;
import java.util.Locale;
public class CurrencyLocaleExample {
public static void main(String[] args) {
Currency currency = Currency.getInstance(Locale.JAPAN);
System.out.println("Currency Code: " + currency.getCurrencyCode());
}
}
Output:
Currency Code: JPY
4. Conclusion
The Currency
class in Java is used for applications that need to handle monetary values. It provides information about currency codes, symbols, and fractional digits, making it essential for financial and internationalized applications.
Comments
Post a Comment
Leave Comment