Java ProgramsControl FlowCurrency Converter Using Switch

Currency Converter Using Switch in Java

intermediate·  Control Flow  ·  Switch Statement

Problem

A switch statement can map a currency code directly to its fixed conversion rate, keeping the lookup separate from the multiplication that applies it.

Given a currency code and an amount, convert it to a target currency using a fixed set of illustrative exchange rates.

Input
currency = "USD", amount = 100.0
Output
Converted amount: 8300.0

Java Program

Java
public class CurrencyConverterSwitch { public static void main(String[] args) { String currency = "USD"; double amount = 100.0; double rate; switch (currency) { case "USD": rate = 83.0; break; case "EUR": rate = 90.0; break; case "GBP": rate = 105.0; break; default: rate = 0.0; // unrecognized currency code } double converted = amount * rate; System.out.println("Converted amount: " + converted); } }

Output

Converted amount: 8300.0

Core Logic

Matching the currency code against each case picks out its fixed rate, then a single multiplication applies it to the amount.

How It Works
  1. 1switch (currency) matches the currency code string against each case label.
  2. 2"USD" resolves to a rate of 83.0, "EUR" to 90.0, and "GBP" to 105.0 — illustrative fixed rates, not live market rates.
  3. 3The default case assigns 0.0, signaling an unrecognized currency code without throwing.
  4. 4Once rate is resolved, amount * rate computes the converted amount.
For currency = "USD" and amount = 100.0, the switch resolves rate to 83.0, giving a converted amount of 8300.0.
💡

Key Point: These rates are fixed, illustrative constants for demonstrating a switch-based lookup — a real converter would need to pull live rates from an external source.

Key Concepts

switch statementString switchdefault case

Related Programs