Pages

Sunday, December 26, 2021

 Concept

    To test more than one condition, an if statement can be nested inside another if statement.

Syntax

if(BooleanExpression 1) {
   // Executes when the Boolean expression 1 is true
   if(BooleanExpression 2) {
      // Executes when the Boolean expression 2 is true
   }
}

Logic




How nested if works?

If the expression 1 is true, however, we need to test the second condition. If the expression 2 is true, 
we need to test the third condition and so on. The statements within the true block will get executed.
And then the execution continues with the next statements following the if.

Example (Test.java)

public class Test {

   public static void main(String args[]) {
      int x = 30;
      int y = 10;

      if( x == 30 ) {
         if( y == 10 ) {
            System.out.print("X = 30 and Y = 10");
         }
      }
   }
}

Output

X = 30 and Y = 10

No comments:

Post a Comment