Java

 

 

Introduction: In today’s globalized world, currency exchange plays a crucial role in international trade and finance. A currency exchange app allows users to track and convert currency rates between different countries. In this article, we will learn how to create a simple currency exchange app using Java, which fetches real-time exchange rates and performs conversions. The app will allow users to input an amount in one currency and convert it to another currency based on the current exchange rate.

Objective: The goal of this project is to build a currency exchange application in Java that fetches live exchange rates from an API and allows users to convert currency values between different currencies.

Code:

import java.net.*;
import java.io.*;
import org.json.JSONObject;

public class CurrencyExchangeApp {

    public static void main(String[] args) {
        try {
            // API URL to get exchange rates
            String urlString = "https://api.exchangerate-api.com/v4/latest/USD";
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // Reading response from API
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // Parsing the JSON response
            JSONObject myResponse = new JSONObject(response.toString());
            JSONObject rates = myResponse.getJSONObject("rates");

            // Example: Convert USD to EUR
            double usdAmount = 100;  // Example amount
            double conversionRate = rates.getDouble("EUR"); // USD to EUR
            double convertedAmount = usdAmount * conversionRate;

            // Display the result
            System.out.println(usdAmount + " USD = " + convertedAmount + " EUR");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation of the Program:

This program retrieves exchange rates from an external API (https://api.exchangerate-api.com) in JSON format. The currency exchange rates are based on USD as the base currency. Here is how the program works:

  • API Request: The program first makes an HTTP GET request to the API URL to fetch the latest exchange rates.
  • Reading and Parsing the Response: The response is read and parsed as a JSON object using the org.json library.
  • Exchange Rate Retrieval: The program extracts the exchange rate for EUR (Euros) from the JSON response.
  • Currency Conversion: The user can specify an amount in USD, which is then multiplied by the exchange rate for EUR to convert the currency.
  • Output: The converted amount is printed to the console.

How to Run the Program:

  1. Download and install the Java Development Kit (JDK) from the official Oracle website if you don’t have it already.
  2. Download the org.json library from the official website or use a dependency manager like Maven or Gradle to include it in your project.
  3. Create a new Java file (CurrencyExchangeApp.java) and paste the code provided above.
  4. Compile the program by running the following command in your terminal/command prompt:
    javac CurrencyExchangeApp.java
  5. Run the program by executing:
    java CurrencyExchangeApp
  6. View the output in the terminal, which will display the conversion rate and result (in this case, USD to EUR).

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)