Tech career with our top-tier training in Data Science, Software Testing, and Full Stack Development.
phone to 4Achievers +91-93117-65521 +91-801080-5667
Navigation Icons Navigation Icons Navigation Icons Navigation Icons Navigation Icons Navigation Icons Navigation Icons

+91-801080-5667
+91-801080-5667
Need Expert Advise, Enrol Free!!
Share this article

Currency Converter Java App with Code and Full Guide

Full Guide to Set-up The Project in java

Step 1: Install Java Development Kit (JDK)

For Windows:

Download JDK:

Install JDK:

  • Double-click the installer and follow the prompts to install Java.
  • Remember the installation path, e.g., C:\Program Files\Java\jdk-17.

Set JAVA_HOME (for Windows):

  • Open the Start menu and search for "Environment Variables".
  • Click "Edit the system environment variables".
  • Under "System Properties," click on Environment Variables.
  • Click New under System variables.
    • Variable Name: JAVA_HOME
    • Variable Value: path to your JDK (e.g., C:\Program Files\Java\jdk-17).
  • In the "Path" variable, add the following:
    • %JAVA_HOME%\bin

Verify Installation:

Open Command Prompt and type
java -version
javac -version
Step 2: Install an IDE (Integrated Development Environment)

IntelliJ IDEA is the most popular IDE for Java.

Download IntelliJ IDEA:

Install IntelliJ IDEA:

  • Follow the installation steps for your system.

Configure IntelliJ:

  • When you first open IntelliJ IDEA, it will ask you to configure JDK. Select the JDK you installed earlier.

Step 3: Create a Java Project

Create a new project:

  • Open IntelliJ IDEA and click on Create New Project.
  • Select Java under "New Project".
  • Ensure the JDK you installed is selected. Click Next.

Name the project:

  • Enter a name for your project (e.g., HelloWorld), and choose a location to save it. Click Finish.

Step 4: Write Java Code

Create a Java Class:

  • Inside your new project, go to the src folder.
  • Right-click on src, and choose New > Java Class.
  • Name the class Main, and click OK.

Write your Java code:

Inside Main.java, write a simple program like this:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}


Step 5: Run the Project

  1. Run the program:
    • Click the green run button at the top right, or press Shift + F10.
    • You should see "Hello, World!" in the console at the bottom.

Create A Currency Converter Full Functional app with Use of Java Full Guide

Creating a Currency Converter app in Java involves several steps. Below is a complete guide with the full code for a Currency Converter app using Java and Swing for the user interface. This example uses an API (for real-time currency conversion rates) to get exchange rates.

Steps:

  1. Set up your Java environment (IDE, JDK).
  2. Create a simple GUI using Java Swing.
  3. Fetch exchange rates from an API.
  4. Display conversion results based on user input.

Prerequisites:

  1. Java JDK installed.
  2. JSON parsing library (we'll use org.json for simplicity).
  3. API for currency exchange rates (such as ExchangeRate-API or Open Exchange Rates).

Step-by-Step Guide:

1. Create the Java Project:

Set up your Java project in your preferred IDE (like IntelliJ IDEA, Eclipse, etc.).

2. Add JSON Parsing Dependency:

If you're using Maven, add this dependency to pom.xml for JSON parsing:

org.json
json
20210307

Alternatively, you can manually download the JSON jar and add it to your project.

3. Java Code Implementation:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class CurrencyConverterApp {

// GUI Components
private JFrame frame;
private JTextField amountField;
private JComboBox fromCurrencyBox;
private JComboBox toCurrencyBox;
private JTextField resultField;
private JButton convertButton;

public static void main(String[] args) {
// Run the application
SwingUtilities.invokeLater(() -> {
try {
CurrencyConverterApp window = new CurrencyConverterApp();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}

public CurrencyConverterApp() {
// Create the window
frame = new JFrame("Currency Converter");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());

// Amount field for input
JLabel amountLabel = new JLabel("Amount:");
frame.getContentPane().add(amountLabel);

amountField = new JTextField();
amountField.setColumns(10);
frame.getContentPane().add(amountField);

// From currency dropdown
JLabel fromLabel = new JLabel("From Currency:");
frame.getContentPane().add(fromLabel);

String[] currencies = {"USD", "EUR", "GBP", "INR", "AUD", "JPY"};
fromCurrencyBox = new JComboBox<>(currencies);
frame.getContentPane().add(fromCurrencyBox);

// To currency dropdown
JLabel toLabel = new JLabel("To Currency:");
frame.getContentPane().add(toLabel);

toCurrencyBox = new JComboBox<>(currencies);
frame.getContentPane().add(toCurrencyBox);

// Result field
JLabel resultLabel = new JLabel("Converted Amount:");
frame.getContentPane().add(resultLabel);

resultField = new JTextField();
resultField.setEditable(false);
resultField.setColumns(10);
frame.getContentPane().add(resultField);

// Convert button
convertButton = new JButton("Convert");
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
convertCurrency();
}
});
frame.getContentPane().add(convertButton);
}

// Fetch exchange rates and convert currency
private void convertCurrency() {
try {
String fromCurrency = fromCurrencyBox.getSelectedItem().toString();
String toCurrency = toCurrencyBox.getSelectedItem().toString();
double amount = Double.parseDouble(amountField.getText());

// API URL for real-time exchange rates (Replace API_KEY with your actual key)
String apiKey = "YOUR_API_KEY";
String urlString = String.format("https://v6.exchangerate-api.com/v6/%s/latest/%s", apiKey, fromCurrency);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

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

// Parse the response
JSONObject jsonResponse = new JSONObject(response.toString());
JSONObject conversionRates = jsonResponse.getJSONObject("conversion_rates");
double rate = conversionRates.getDouble(toCurrency);

// Calculate the converted amount
double result = amount * rate;
resultField.setText(String.format("%.2f", result));
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Error: Unable to fetch conversion rate or invalid input.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
Explanation of Code:

GUI Components:

  • We use JFrame for the window.
  • JTextField for entering the amount and showing the result.
  • JComboBox for selecting the "From" and "To" currencies.
  • JButton to trigger the conversion.

Currency Conversion Logic:

  • When the user presses the "Convert" button, the convertCurrency() method is triggered.
  • It fetches real-time exchange rates from an external API (here, ExchangeRate-API).
  • The JSON response is parsed, and the conversion rate for the selected currencies is extracted.
  • The amount entered is multiplied by the conversion rate and the result is displayed.

API Request:

  • The URL used for fetching exchange rates is: https://v6.exchangerate-api.com/v6/YOUR_API_KEY/latest/{fromCurrency}.
  • Make sure to replace YOUR_API_KEY with your actual API key.

Error Handling:

  • If there is an error fetching data from the API or invalid user input, an error message is shown.

Running the Application:

  1. Replace API Key: Make sure to replace YOUR_API_KEY with a real API key from an exchange rate API provider like ExchangeRate-API.
  2. Compile and Run: Compile the Java code and run the CurrencyConverterApp. The GUI will pop up, allowing users to input an amount, select currencies, and get the conversion result.

Further Enhancements:

  • You can add more currencies to the dropdown list.
  • Add more error handling for invalid or empty inputs.
  • Make the UI more sophisticated by adding labels, tooltips, and custom icons.

This simple Currency Converter app demonstrates how you can use Java for GUI development and integrate real-time data from external APIs.

Aaradhya, an M.Tech student, is deeply engaged in research, striving to push the boundaries of knowledge and innovation in their field. With a strong foundation in their discipline, Aaradhya conducts experiments, analyzes data, and collaborates with peers to develop new theories and solutions. Their affiliation with "4achievres" underscores their commitment to academic excellence and provides access to resources and mentorship, further enhancing their research experience. Aaradhya's dedication to advancing knowledge and making meaningful contributions exemplifies their passion for learning and their potential to drive positive change in their field and beyond.

Explore the latest job openings

Looking for more job opportunities? Look no further! Our platform offers a diverse array of job listings across various industries, from technology to healthcare, marketing to finance. Whether you're a seasoned professional or just starting your career journey, you'll find exciting opportunities that match your skills and interests. Explore our platform today and take the next step towards your dream job!

See All Jobs

Explore the latest blogs

Looking for insightful and engaging blogs packed with related information? Your search ends here! Dive into our collection of blogs covering a wide range of topics, from technology trends to lifestyle tips, finance advice to health hacks. Whether you're seeking expert advice, industry insights, or just some inspiration, our blog platform has something for everyone. Explore now and enrich your knowledge with our informative content!

See All Bogs

Enrolling in a course at 4Achievers will give you access to a community of 4,000+ other students.

Email

Our friendly team is here to help.
Info@4achievers.com

Phone

We assist You : Monday - Sunday (24*7)
+91-801080-5667
Register for Free Demo
By clicking the button above, you agree to our Terms of Use and Privacy Policy. We do not share this information.

Whatsapp

Call