Java program for nested if statement

Introduction

We use nested if-else statements when multiple decisions are involved in the java program. We can nest many if statements or if-else statements in the program based on the decisions. We can use one if or if-else statement inside another if/if-else statement

Syntax

The sample syntax of nested if statement in the simplest form is :

If (Boolean_expression 1)

{

//Executes when the Boolean expression 1 is true

        If (Boolean_expression 2)

       {

        //Executes when the Boolean expression 2 is true

         }

}

 

 

Java Program

We will write a simple java program to show the syntax usage of the nested if in a Java program.

/*********************************************************** * NestedIf.java * @program : Java program using nested if loop * @web : www.testingdocs.com * @version : 1.0 ************************************************************/
public class NestedIfStatement { public static void main(String[] args) { int a = 10; int b = 20; if(a == 10) { if(b == 20) { System.out.println("b value is " + b); } System.out.println("a value is " + a); } }
}

 

In this program, two variables a & b are initialized to some arbitrary values. Using nested if statement the output of the variables is printed.

Program Output

b value is 20
a value is 10

Screenshot

 

 

Another Example

/*********************************************************** * NestedIf.java * @program : Java program using nested if loop * @web : www.testingdocs.com * @version : 1.0 ************************************************************/
public class NestedIfStatement { public static void main(String[] args) { int a = 10; int b = 5; int c = 3; if(a > b) { if(c > b) System.out.println("b is the minimum of the three values."); else { if(a > c ) System.out.println("c is the minimum of the three values."); } }else { if(c > a) System.out.println("a is the minimum of the three values."); } }
}

Output:

c is the minimum of the three values.