Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - For Statement



The for statement is used to iterate through a set of values. The for statement is generally used in the following way.

for(variable declaration;expression;Increment) { 
   statement #1 
   statement #2 
    
}

The classic for statement consists of the following parts −

  • Variable declaration − This step is executed only once for the entire loop and used to declare any variables which will be used within the loop.

  • Expression − This will consists of an expression which will be evaluated for each iteration of the loop.

  • The increment section will contain the logic needed increment the variable declared in the for statement.

The following diagram shows the diagrammatic explanation of this loop.

For Loop

Example - Basic Usage of for Statement

Following is an example of the classic for statement −

Example.groovy

class Example { 
   static void main(String[] args) {	
      for(int i = 0;i<5;i++) {
         println(i);
      }		
   }
}

Explanation

In the above example, we are in our for loop doing three things −

  • Declaring a variable i and Initializing the value of i to 0

  • Putting a conditional expression that the for loop should execute till the value of i is less than 5.

  • Increment the value of i by 1 for each iteration.

Output

The output of the above code would be −

0 
1 
2 
3 
4 

Example - Printing List Elements Using for Loop

Following is an example of the iterating list elements using for statement −

Example.groovy

class Example {

   static void main(String[] args) {
      def numbers = [10, 20, 30, 40, 50];

      for(int index = 0; index < numbers.size(); index++) {
         println("value of item : " + numbers[index] );
      }
   }
}

Output

The output of the above code would be −

value of item : 10
value of item : 20
value of item : 30
value of item : 40
value of item : 50

Explanation

In this example, we're showing the use of a for loop to print contents of a list. Here we're creating an list of integers as numbers and initialized it some values. We've created a variable named index to represent index of the list within for loop, check it against size of the list and incremented it by 1. Within for loop body, we're printing element of the list using index notation. Once index becomes same as list size, for loop exits and program quits.

Example - Nested for Loops

Following is an example of using nested for loop statement useful to create/iterate matrices−

Example.groovy

class Example {
    static void main(String[] args) {
        for(int i = 1; i <= 3; i++) {
            for(int j = 1; j <= 3; j++) {
                print(i + "," + j + " ");
            }
            println();
        }
    }
}

Output

The output of the above code would be −

1,1 1,2 1,3 
2,1 2,2 2,3 
3,1 3,2 3,3 
Advertisements