Convert Units Using Switch in Java
Problem
Each unit conversion is its own fixed formula, so switching on a conversion-type String lets each case apply the one formula it's responsible for.
Given a value and a conversion type, convert the value using that conversion's formula.
Java Program
public class UnitConverterSwitch {
public static void main(String[] args) {
String conversionType = "c-to-f";
double value = 25.0;
double converted;
switch (conversionType) {
case "c-to-f":
converted = value * 9 / 5 + 32;
break;
case "km-to-miles":
converted = value * 0.621371;
break;
case "kg-to-pounds":
converted = value * 2.20462;
break;
default:
throw new IllegalArgumentException("Unknown conversion type: " + conversionType); // no break needed — throw exits immediately
}
System.out.println("Converted value: " + converted);
}
}Output
Core Logic
Matching the conversion-type string against each case label routes the value to the one formula that conversion actually needs.
- 1
switch (conversionType)compares the String against case labels"c-to-f","km-to-miles", and"kg-to-pounds". - 2
"c-to-f"appliesvalue * 9 / 5 + 32, the standard Celsius-to-Fahrenheit formula. - 3
"km-to-miles"and"kg-to-pounds"each multiply by their own fixed conversion factor. - 4The
defaultcase throws an exception for an unrecognized conversion type.
conversionType = "c-to-f" and value = 25.0, the first case computes 25.0 * 9 / 5 + 32 = 77.0.Key Point: The conversion factors themselves — 0.621371, 2.20462 — are fixed physical constants, not values this program chooses; only which formula runs depends on the switch.
Key Concepts
Approach 2: Java 8
import java.util.Map;
import java.util.function.DoubleUnaryOperator;
public class UnitConverterMapLookup {
public static void main(String[] args) {
String conversionType = "c-to-f";
double value = 25.0;
Map<String, DoubleUnaryOperator> conversions = Map.of( // pairs each conversion type with its formula
"c-to-f", v -> v * 9 / 5 + 32,
"km-to-miles", v -> v * 0.621371,
"kg-to-pounds", v -> v * 2.20462
);
double converted = conversions.get(conversionType).applyAsDouble(value);
System.out.println("Converted value: " + converted);
}
}
Output
Core Logic
A map from conversion type to formula replaces the switch entirely — looking up the right function and calling it does the same dispatch in one line.
- 1
Map.of(...)builds an immutable map pairing each conversion-type string with aDoubleUnaryOperatorlambda. - 2
conversions.get(conversionType)retrieves the lambda matching the given type. - 3
.applyAsDouble(value)calls that lambda with the input value, producing the converted result directly.
conversionType = "c-to-f", the map returns the Celsius-to-Fahrenheit lambda, and calling it with 25.0 gives 77.0.Key Point: Adding a new conversion here means adding one more map entry, not another case block — the dispatch logic itself never changes.