Groovy - Nested If Statement



Sometimes there is a requirement to have multiple if statement embedded inside of each other.

The general form of this statement is −

if(condition) { 
   statement #1 
   statement #2 
   ... 
} else if(condition) { 
   statement #3 
   statement #4 
} else { 
   statement #5 
   statement #6 
}

Following is an example of a nested if/else statement −

class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 12 
		
      //Check for the boolean condition 
      if (a>100) {
         //If the condition is true print the following statement 
         println("The value is less than 100"); 
      } else 
         // Check if the value of a is greater than 5 
			
      if (a>5) { 
         //If the condition is true print the following statement 
         println("The value is greater than 5 and greater than 100"); 
      } else { 
         //If the condition is false print the following statement 
         println("The value of a is less than 5"); 
      }  
   } 
}	     

In the above example, we are first initializing a variable to a value of 12. In the first if statement, we are seeing if the value of a is greater than 100. If not, then we enter our second for loop to see if the value of a is greater than 5 or less than 5. The output of the above code would be −

The value is greater than 5 and greater than 100
groovy_decision_making.htm
Advertisements