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

*Learn Spring*course:

Last modified: October 1, 2022

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.

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 |
Underweight |

18.5 - 25 |
Normal |

25 - 30 |
Overweight |

> 30 |
Obese |

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”.**

The Java program consists of the formula for calculating BMI and simple *if*–*else* 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";
}
}
```

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

```
@Test
public void whenBMIIsGreaterThanThirty_thenObese() {
double weight = 50;
double height = 1.524;
String actual = BMICalculator.calculateBMI(weight, height);
String expected = "Obese";
assertThat(actual).isEqualTo(expected);
}
```

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

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.

Login

0 Comments

Follow the Java Category

Follow the Java category to get regular info about the new articles and tutorials we publish here.