Skip to content
Groovy 12 - Loops

Types of Loops

There are 3 types of loops:

  • while loop
  • do-while loop
  • for loop

while Loop

        while (condition) {
            // execute some code
        }
        

As long as the condition is true, the code inside the brackets will keep executing.

Example:

        while (var_x <= 10) {
            println(var_x)
            var_x++
        }
        

Output:

        0
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        

do-while Loop

        do {
            // execute some code
        } while (condition)
        

The code inside the brackets will execute at least once and then continue executing as long as the condition is true.

Example:

        int var_x = 80
        do {
            println(var_x)
            var_x++
        } while (var_x <= 10)
        

Output:

        80
        

for Loop

        for (initialization; condition; increment) {
            // execute some code
        }
        

First, we start with a value (initialization), then a condition is placed, so the code executes as long as the condition is true, and then that value gets incremented.

Example:

        for (int i = 0; i <= 10; i++) {
            println(i)
        }
        

Output:

        0
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        

When to Use Them

Use while loop when you don't know exactly how long you want some code to keep executing.

Use do-while when you want your code to execute at least once, regardless of whether the condition is true or false. So do-while is used when you want some code to be executed at least once.

Use for loop when you know precisely how long you want to execute some code and from where to start.

Special Case of for Loop: for-each

        for (variable : collection) {
            // code to execute
        }
        

This loop is used to make your code compact and helps when you need to cycle through a collection of data. It also helps in reducing the risk of programming errors.

Example:

        int[] var_array = {1, 2, 3, 4}
        for (int i : var_array) {
            println(i)
        }
        

Output:

        1
        2
        3
        4
        

Infinite Loop

An infinite loop is a cycle that never ends, so the environment will give you an error like:

oracle.jbo.ExprTimeoutException Expression timed out.

Example of an infinite loop:

        def var_x = 80
        while (var_x) {
            println(var_x)
        }