Build a Currency Converter CLI in Java in Under 30 Minutes
If you’ve ever needed to convert currencies on the fly, building a command-line interface (CLI) tool in Java can be a quick and powerful solution. In this post, we’ll show you how to create a currency converter CLI in Java using real-time exchange rates from an open API – all in under 30 minutes. You’ll learn to use Java’s HTTPClient, handle JSON responses, and cleanly build a Java console app that takes user input and converts currencies accurately.
Let’s break it down step-by-step:
1. Setting Up Your Java Project
First, ensure you’re using Java 11 or higher to take advantage of the built-in HttpClient
API. Also, we’ll use the popular org.json
or Gson
library to parse JSON.
Directory structure:
CurrencyConverterCLI/
├── src/
│ └── Main.java
├── lib/
└── build.sh
Add a JSON library. For example, download org.json or use Gson and place the JAR in your lib
folder.
Example build.sh
to compile:
#!/bin/bash
javac -cp "lib/*" src/Main.java -d .
java -cp ".:lib/*" Main
2. Making an HTTP Request to Fetch Real-Time Rates
We’ll use the ExchangeRate.host API, which requires no authentication and returns current exchange rates in JSON format:
API endpoint example:
https://api.exchangerate.host/latest?base=USD&symbols=EUR
Java code to make this HTTP GET request using HttpClient
:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class CurrencyFetcher {
public static String getRates(String base, String target) throws Exception {
String url = String.format("https://api.exchangerate.host/latest?base=%s&symbols=%s", base, target);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
}
3. Parsing the JSON Response
Use org.json or Gson to parse the returned JSON string. Here’s how to extract the exchange rate value.
Using org.json:
import org.json.JSONObject;
public class RateParser {
public static double parseRate(String json, String targetCurrency) {
JSONObject obj = new JSONObject(json);
JSONObject rates = obj.getJSONObject("rates");
return rates.getDouble(targetCurrency);
}
}
This code safely extracts the target currency’s exchange rate from the JSON string. Always validate that the target exists to prevent JSONException
.
4. Building the Main CLI Application
We’ll now combine everything into a simple console app that gets user input, retrieves the rate, performs the conversion, and displays the result.
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter base currency (e.g. USD): ");
String base = scanner.nextLine().toUpperCase();
System.out.print("Enter target currency (e.g. EUR): ");
String target = scanner.nextLine().toUpperCase();
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
String json = CurrencyFetcher.getRates(base, target);
double rate = RateParser.parseRate(json, target);
double converted = amount * rate;
System.out.printf("%.2f %s = %.2f %s\n", amount, base, converted, target);
}
}
This CLI reads currency codes and amounts from the user and displays a neatly formatted output with the converted amount. For example:
Enter base currency (e.g. USD): USD
Enter target currency (e.g. EUR): EUR
Enter amount: 100
100.00 USD = 92.34 EUR
5. Best Practices, Tips, and Enhancements
Here are some additional pointers to improve accuracy, performance, and usability:
- Exception Handling: Wrap API and parsing logic in try/catch blocks to handle network or format issues.
- Validation: Check if the JSON contains error messages or invalid currency codes before attempting to parse them.
- Performance: Cache the most recent rates locally if you plan to make multiple conversions using the same base.
- Extensibility: Add support for command-line flags to provide values upfront (e.g.,
--base USD --target EUR --amount 200
). - Offline Support: Store the latest successful response on disk and use it when offline for approximate conversions.
Conclusion
In less than 30 minutes, we’ve created a clean and functional currency converter CLI in Java that fetches live data from a free public API. Using Java’s HttpClient
and a lightweight JSON parser makes the app efficient and extensible. Great for learning, scripting, or even building into larger applications!
Happy coding!
Useful links: