Home Java JDK 8 Features Spring Boot React JS Servlet Data JPA JDBC Microservices Hibernate

Nested if-else Statement

Nested control statements mean an if-else statement inside other if or else blocks.

 It is similar to an if-else statement but they are defined inside another if-else statement.

 

 

Example-

public class NestedIfElseConcept {

               public static void main(String[] args) {

                              int age = 22;

                              String gender = "female";

                              if (age >= 18) {

                                             if (gender == "male") {

                                                            System.out.println("You can shop in the men's section on the 3rd Floor");

                                             } else {

                                                            System.out.println("You can shop in the women's section on 2nd Floor");

                                             }

                              } else {

                                             System.out.println("You can shop in the kid's section on 1st Floor");

                              }

               }

}

Output:

You can shop in the women's section on 2nd Floor

If-else-If Ladder

In this, the if statement is followed by multiple else-if blocks. We can create a decision tree by using these control statements in Java in which the block where the condition is true is executed and the rest of the ladder is ignored and not executed. If none of the conditions is true, the last else block is executed, if present.

Syntax:

if(condition1) {

    // Executed only when the condition1 is true

}

else if(condition2) {

    // Executed only when the condition2 is true

}

.

.

.

.

else {

    // Executed when all the conditions mentioned above are true

}

Example:

public class IfElseIfLadderConcept {

               public static void main(String[] args) {

                              int marks = 67;

                              if (marks >= 68) {

                                             System.out.println("First Class with Distinction");

                              } else if (marks < 68 && marks >= 60) {

                                             System.out.println("First Class");

                              } else if (marks < 60 && marks >= 55) {

                                             System.out.println("Higher Second Class");

                              } else if (marks < 55 && marks >= 50) {

                                             System.out.println("Secind Class");

                              } else if (marks < 50 && marks >= 40) {

                                             System.out.println("Pass");

                              } else {

                                             System.out.println("Fail");

                              }

               }

}

 

Output: 

First Class