Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - If Statement



The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true, it then executes the statements. The following diagram shows the flow of the if statement.

If Statement

Example - Usage of if statement

Following is an example of a if statement −

Example.groovy

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

Output

In the above example, we are first initializing a variable to a value of 2. We are then evaluating the value of the variable and then deciding whether the println statement should be executed. The output of the above code would be −

The value is less than 100

Example - Usage of if statement with Boolean value

In this example, we're showing the use of a if statement to check if a boolean value is true or false. As x is less than 20, result will be true and the statement within if block will be printed.

Example.groovy

class Example {
   static void main(String[] args) {
      int x = 10;
      boolean result = x < 20;

      if( result ) {
         System.out.print("This is if statement");
      }
   }
}

Output

This is if statement.

Example - Usage of if statement with Boolean as false value

In this example, we're showing the use of a if statement to check if a boolean value is false. As x is not greater than 20, result will be true and the statement within if block will be printed.

Example.groovy

class Example {
   static void main(String[] args) {
      int x = 10;
      boolean result = x > 20;

      if( !result ) {
         System.out.print("This is if statement");
      }
   }
}

Output

This is if statement.
groovy_decision_making.htm
Advertisements