In this article, we will analyze one of the most used commands, the if statement in Java, through detailed examples
1. If, Else If, and Else Statements Syntax
The Java if statements are used when we need to do some actions, based on whether a statement is true or false.
1.1 If statement in Java
The syntax for a simple If statement is the following:
if (expression) { //actions } //In case actions is only one line of code, you can skip the brackets if(expression) //action
The expression must evaluate a boolean
value in order for the code to work. An expression could be, height > 1.80 m, so if the height parameter is 1.60, the actions inside if, will not be executed. On the contrary, if the height is 1.86, the actions will be executed.
1.2 Else statement Java
The syntax of an else
statement is the following:
if(expression){ //actions } else { //actions when statement is false }
The else statement can exist, only if an if statement exists. So like in the previous example, when the height is 1.60, the actions inside the else statement will be executed.
Note that like in if statements, should else statement contains only one line of code, you can skip the brackets.
1.3 Else If statement in Java
The syntax of an else if
statement is the following:
if(expression){ // actions } else if(other_expression_1){ // actions } else if(another_expression_2){ //actions }
The else if statement is exactly like an if statement, but it can only exist if an if statement exists. Like the previous examples, you might want to print another message when the height is higher than 1.60 but lower than 1.75. In that case, the else wouldn’t work. In the next section, we’ll combine the aforementioned statements in a real-world example.
2. If, else if and else statement example in Java
In this section, we will calculate the Body Mass Index(BMI) with the weight and the height of a person as input and then print a message based on the result.
private static void printBMIResultNotOptimized(double height, double weight){ // The formula for BMI is weight / height^2 double BMI = weight/Math.pow(height,2); System.out.println("The Height is: "+ height + " and the Weight is: "+weight); System.out.print("This person is: "); if(BMI < 16) System.out.println("Underweight (Severe thinness)"); else if (BMI >= 16 && BMI < 17) System.out.println("Underweight (Moderate thinness)"); else if (BMI >= 17 && BMI < 18.5) System.out.println("Underweight (Mild thinness)"); else if (BMI >= 18.5 && BMI < 24.9) System.out.println("Normal Range"); else if (BMI >= 24.9 && BMI < 29.9) System.out.println("Overweight (Pre-obese)"); else if (BMI >= 29.9 && BMI < 34.9) System.out.println("Obese (Class I)"); else if (BMI >= 34.9 && BMI < 39.9) System.out.println("Obese (Class II)"); else if (BMI >= 39.9) System.out.println("Obese (Class III)"); }
If you try running the method above, it will work. The problem is that the statements are not optimized. There are 2 improvements that can be applied here.
- If , else if and else, are mutually exclusive, if any of the statements evaluates to true, the rest will not be executed, and if a statement evaluates to false, the program will continue with the rest checks. Having that in mind, we can remove the first check for every else if statement but the last. So the fist else if will become
else if (BMI < 17)
, the second will becomeelse if (BMI < 18.5)
etc. Note that the order is important in case you try this optimization, since if you swap the 1st else if with the 2nd else if, an “Underweight (Severe thinness)” Person, will be printed as “Underweight (Moderate thinness)” person - We can replace the last
else if
with a simpleelse
statement, since we want this to be printed in case all other statements have been evaluated to false.
After the improvements, the method will be the following:
private static void printBMIResultOptimized(double height, double weight){ double BMI = weight/Math.pow(height,2); System.out.println("The Height is: "+ height + " and the Weight is: "+weight); System.out.print("This person is: "); if(BMI < 16) System.out.println("Underweight (Severe thinness)"); else if (BMI < 17) System.out.println("Underweight (Moderate thinness)"); else if (BMI < 18.5) System.out.println("Underweight (Mild thinness)"); else if (BMI < 24.9) System.out.println("Normal Range"); else if (BMI < 29.9) System.out.println("Overweight (Pre-obese)"); else if (BMI < 34.9) System.out.println("Obese (Class I)"); else if (BMI < 39.9) System.out.println("Obese (Class II)"); else System.out.println("Obese (Class III)"); }
We can run the method by providing different heights and weights and then check the results.
public static void main(String[] args) { // In meters double height = 1.70; // In kilograms double weight = 60; printBMIResultOptimized(height, weight); height = 1.75; weight = 45; printBMIResultOptimized(height, weight); height = 2.00; weight = 250; printBMIResultOptimized(height, weight); height = 1.79; weight = 84; printBMIResultOptimized(height, weight); }
The output will be:
The Height is: 1.7 and the Weight is: 60.0 This person is: Normal Range The Height is: 1.75 and the Weight is: 45.0 This person is: Underweight (Severe thinness) The Height is: 2.0 and the Weight is: 250.0 This person is: Obese (Class III) The Height is: 1.79 and the Weight is: 84.0 This person is: Overweight (Pre-obese)
3. Nested If, else If and else statements
If needed, it is possible to write if,else-if and else statements inside other if,else-if and else statements. The syntax the following
if (statement_1) { //actions if (statement_2){ //actions } }
Below, you can find an example:
public static void main(String[] args) { nestedIfsTable(true,true,false); nestedIfsTable(true, false , false); nestedIfsTable(true, false , true); } private static void nestedIfsTable(boolean isBlack, boolean isBroken, Boolean isOld){ if(isBlack){ if(isBroken){ if(!isOld) System.out.println("Table is Black, Broken and Old"); else System.out.println("Table is Black, Broken but not Old"); } else { System.out.println("Table is Black and not Broken"); } } }
The output will be:
Table is Black, Broken and Old Table is Black and not Broken Table is Black and not Broken
We can notice 2 things about nested ifs.
- Nested ifs could lead to reduced readability of code.
- In some cases, we can replace them by moving the expression inside the nested if, inside the parent statement, and connect them with an AND operator. For example
if(isBlack){ if(isBroken){
can be converted to
if(isBlack && isBroken){
4. Conclusion
By now you should be able to use If, Else If, and Else statements in the most efficient ways. You can find the source code on our GitHub page.
Leave a Reply