Area Calculator Using Switch in Java
intermediate· Control Flow · Switch Statement
Problem
Different shapes need entirely different area formulas, so switching on a shape-name String lets each case apply its own formula to its own dimensions.
Given a shape name and its dimensions, calculate that shape's area.
Input
shape = "rectangle", length = 8.0, width = 5.0
Output
Area: 40.0
Java Program
Java
public class AreaCalculatorSwitch {
public static void main(String[] args) {
String shape = "rectangle";
double radius = 3.0; // only the matching case's dimensions are actually used
double side = 4.0;
double length = 8.0, width = 5.0;
double base = 6.0, height = 4.0;
double area;
switch (shape) {
case "circle":
area = Math.PI * radius * radius;
break;
case "square":
area = side * side;
break;
case "rectangle":
area = length * width;
break;
case "triangle":
area = 0.5 * base * height;
break;
default:
throw new IllegalArgumentException("Unknown shape: " + shape);
}
System.out.println("Area: " + area);
}
}Output
Area: 40.0
Core Logic
Matching the shape name against each case label routes to that shape's own formula, using only the dimensions that formula actually needs.
How It Works
- 1
switch (shape)compares the String against case labels"circle","square","rectangle", and"triangle". - 2Each case computes area using only its own relevant variables —
radiusfor circle,sidefor square, and so on. - 3The
defaultcase throws an exception for an unrecognized shape name.
For
shape = "rectangle", the matching case computes length * width = 8.0 * 5.0 = 40.0.💡
Key Point: Switching on a String works the same way as switching on an int or char in Java — the case labels just compare string content instead of a primitive value.
Key Concepts
switch statementString switchdefault case