To get a Currency
instance for a specific currency in Java, you can use the getInstance()
method of the Currency
class. This method takes a Locale
object as an argument and returns a Currency
instance for the currency associated with the locale.
Here's an example of how you could use the getInstance()
method to get a Currency
instance for the US dollar:
import java.util.Currency; import java.util.Locale; Currency currency = Currency.getInstance(Locale.US); System.out.println("Currency code: " + currency.getCurrencyCode()); System.out.println("Currency symbol: " + currency.getSymbol());
This code will output the following:
Currency code: USD Currency symbol: $
You can also use the getInstance()
method to get a Currency
instance for a specific currency code. For example:
Currency currency = Currency.getInstance("EUR"); System.out.println("Currency code: " + currency.getCurrencyCode()); System.out.println("Currency symbol: " + currency.getSymbol());
This code will output the following:
Currency code: EUR Currency symbol: €
Note that the Currency
class is not thread-safe, so you should not use a single Currency
instance concurrently from multiple threads. Instead, you should create a new instance for each thread, or use thread-local variables to store the Currency
instances.