Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Decision Making



Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Sr.No. Statements & Description
1 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.

2 if/else 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 thereafter and stops before the else condition and exits out of the loop. If the condition is false it then executes the statements in the else statement block and then exits the loop.

3 Nested If Statement

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

4 Switch Statement

Sometimes the nested if-else statement is so common and is used so often that an easier statement was designed called the switch statement.

5 Nested Switch Statement

It is also possible to have a nested set of switch statements.

The ? : Operator

The conditional operator ? : can be used to replace if...else statements. It has the following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

To determine the value of the whole expression, initially exp1 is evaluated.

  • If the value of exp1 is true, then the value of Exp2 will be the value of the whole expression.

  • If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression.

Example

In this example, we're creating two variables a and b and using ternary operator we've decided the values of b and printed it.

Example.groovy

class Example { 
   static void main(String[] args) { 
      int a, b;
      a = 10;
      b = (a == 1) ? 20: 30;
      println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      println( "Value of b is : " + b );
   }
}

Output

Value of b is : 30
Value of b is : 20
Advertisements