Control structures

In this section, we will discuss the basic control structures, namely the if…else statement, the switch statement, the for loop, and the while loop.

The if-else condition

The if…else condition in Groovy is similar to Java with one exception, how Groovy evaluates the logical if condition. In the following example, the if condition is evaluated true for both Boolean and int values. In Groovy, non-zero integers, non-null values, nonempty strings, initialized collections, and a valid matcher are evaluated as Boolean true values. This is known as Groovy Truths. Let's take a look at the following code:

def condition1 = true int condition2 = 0 if(condition1){ println("Condition 1 satisfied") if(condition2){ println("Condition 2 satisfied") ...

Get Mastering Gradle now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.