Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

In this tutorial, we'll create a BMI Calculator in Java.

Before moving on to the implementation, first, let's understand the concept of BMI.

2. What Is BMI?

BMI stands for Body Mass Index. It's a value derived from an individual's height and weight.

With the help of BMI, we can find out whether an individual's weight is healthy or not.

Let's have a look at the formula for calculating BMI:

BMI = Weight in Kilograms / (Height in Meters * Height in Meters)

A person's categorized as Underweight, Normal, Overweight, or Obese based on the BMI range:

BMI Range Category
< 18.5
18.5 - 25
25 - 30
> 30

For example, let's calculate the BMI of an individual with a weight equal to 100kg (Kilograms) and a height equal to 1.524m (Meters).

BMI = 100 / (1.524 * 1.524)

BMI =  43.056

Since BMI is greater than 30, the person is categorized as “Overweight”.

3. Java Program to Calculate BMI

The Java program consists of the formula for calculating BMI and simple ifelse statements. Using the formula and the table above, we can find out the category an individual lies in:

static String calculateBMI(double weight, double height) {

    double bmi = weight / (height * height);

    if (bmi < 18.5) {
        return "Underweight";
    else if (bmi < 25) {
        return "Normal";
    else if (bmi < 30) {
        return "Overweight";
    else {
       return "Obese";

4. Testing

Let's test the code by providing the height and weight of an individual who is “Obese”:

public void whenBMIIsGreaterThanThirty_thenObese() {
    double weight = 50;
    double height = 1.524;
    String actual = BMICalculator.calculateBMI(weight, height);
    String expected = "Obese";


After running the test, we can see that the actual result is the same as the expected one.

5. Conclusion

In this article, we learned to create a BMI Calculator in Java. We also tested the implementation by writing a JUnit test.

As always, the complete code for the tutorial is available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Inline Feedbacks
View all comments