Calculate BMI in Java
Problem
Body mass index (BMI) is weight in kilograms divided by the square of height in metres; the result is grouped into ranges such as normal weight (18.5 to just under 25).
Given a weight in kilograms and a height in metres, calculate the BMI, round it to one decimal place and print its category.
Java Program
public class CalculateBmi {
public static void main(String[] args) {
double weightKg = 68;
double heightM = 1.75;
double bmi = weightKg / (heightM * heightM); // weight divided by height squared
String category;
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 25) {
category = "Normal weight";
} else if (bmi < 30) {
category = "Overweight";
} else {
category = "Obese";
}
System.out.printf("BMI: %.1f%n", bmi);
System.out.println("Category: " + category);
}
}Output
Core Logic
The formula gives a single number, and an else-if ladder checks it against the category boundaries from lowest to highest.
- 1
weightKg / (heightM * heightM)applies the BMI formula; the parentheses make sure height is squared first. - 2The ladder tests
bmi < 18.5, then< 25, then< 30, falling through to Obese. - 3Because each test runs only if the earlier ones failed, every branch only needs its upper limit.
- 4
printf("%.1f%n")prints the BMI rounded to one decimal place.
Key Point: Without the parentheses, weightKg / heightM * heightM divides and then multiplies back, giving the original weight instead of a BMI.
Key Concepts
Approach 2: Imperial Units (Pounds and Inches)
public class CalculateBmiImperial {
public static void main(String[] args) {
double weightLb = 160;
double heightIn = 68;
double bmi = 703 * weightLb / (heightIn * heightIn); // 703 converts lb/in² to kg/m²
System.out.printf("BMI: %.1f%n", bmi);
System.out.println("Category: " + (bmi < 18.5 ? "Underweight"
: bmi < 25 ? "Normal weight"
: bmi < 30 ? "Overweight" : "Obese"));
}
}
Output
Core Logic
With pounds and inches the formula keeps its shape; a constant factor of 703 converts the result into the same scale as the metric formula.
- 1
703 * weightLb / (heightIn * heightIn)computes BMI from imperial units. - 2The category is chosen with a chain of ternary operators instead of an if-else ladder.
- 3The same boundaries (18.5, 25, 30) apply, because the factor already matches the metric scale.
Key Point: Nested ternaries are compact but hard to read beyond three or four branches — the if-else ladder in the main program is easier to maintain.
Key Concepts
Interview Questions
How do you round the BMI to one decimal place for storage?
Math.round(bmi * 10) / 10.0 returns a rounded double. printf("%.1f") only rounds what's printed.
Is BMI a complete health measure?
No. It doesn't distinguish muscle from fat, so it's a rough screening number — fine for a programming exercise, not a diagnosis.