---
title: "Control structures in Groovy"
canonical: "https://support.appfire.com/space/JMWE/461440031/Control%20structures%20in%20Groovy"
format: markdown
---
> Macro (aura-html)

<span style="color: #000000">To execute a block of code once or a multiple times based on a condition, you would need Control structures. </span>Groovy supports the usual 

- <span style="color: #000000">Conditional statements:</span>` if-else, ``"nested" if then else if, switch, try-catch-finally`
- <span style="color: #222222">Looping statements: </span>`for, for in, while loop`
- <span style="color: #222222">Branching statements: </span>`break, continue, return`

<span style="color: #222222">See </span>[<span style="color: #222222">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_control_structures)<span style="color: #222222"> for more information on the Control structures.</span>

<span style="color: #222222">**On this page:**</span>


### **Conditional statements**

Conditional statements execute a set of statements only if the condition is true

**if**

<span style="color: #000000">The</span>` if `<span style="color: #000000">executes the statements if the condition is </span>`true`<span style="color: #000000">. </span>The notable specialty of` if` in Groovy is, it plays well with the optional `return` statement.<span style="color: #000000"> If your last expression of a method or closure (discussed later) is an </span>`if statement`<span style="color: #000000">, then it is evaluated like an expression.</span>

```groovy
def x = 2

//Simple if
if(x==2){
  false
}

//Simple if else
if(x == 2){
  x = x + 2
}
else{
  x = x - 2
}

//Nested if
if (x) {
    x = x + 1
} else if (y) {
    y = y + 1
} else {
    0
}

//Assign and test in nested expression
if ((x = 3)) {
 return true
}

//Optional return statement
def sysName = "Windows"
if (sysName.contains("Windows"))
 "We're on Windows."
 else
 "Oh, well we are on Mac"
```


**<span style="color: #222222">Switch statement</span>**<span style="color: #222222"> </span>

<span style="color: #222222">The switch statement </span><span style="color: #000000">executes one statement from multiple conditions. It is like </span>`if-else-if`<span style="color: #000000"> ladder statement. </span>The switch statement in Groovy can handle any kind of switch value and different kinds of matching can be performed.

```groovy
def a = 5
def log = ""
switch (a) {
 case 0 : log += "0" //|#1 fall
 case "Demo" : log += "Demo" //String
 case [2,3,5] : log += 5 
 case 5..10 : log += "Range" //Range
 case ~/d/ : log += "Regexmatch" //Regex
 case 1 : log += "1" //|#1 through
 case 2 : log += "2"; break
 default : log += 'default'
}
log == "5RangeRegexmatch12" //returns true
```

**try-catch-finally**

<span style="color: #000000">Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. </span>You can specify a complete `try-catch-finally` sequence of blocks, or just `try-catch`, or just `try-finally` to handle them. Braces are *required* around the block bodies whether or not they contain more than one statement.

```groovy
def myMethod() {
 throw new IllegalArgumentException()
}
def log = []
try {
 myMethod()
} catch (Exception e) {
 log << e.toString()
} finally {
 log << "finally"
}
log.size() == 2 //returns true
```

### **<span style="color: #222222">Looping statements</span>**

<span style="color: #222222">Looping repeats the execution of a block of code multiple times. The loops available in Groovy are:</span>

<span style="color: #222222">**while loop**</span>

<span style="color: #222222">In a while loop the boolean test is evaluated, and if it's true, the body of the loop is then executed.</span>

```groovy
def list = [1, 2, 3]
while (list){
  list.remove(0)
}
list // returns []
```

**do-while loop**

Starting in [Groovy 3](https://groovy-lang.org/releasenotes/groovy-3.0.html), do-while loops are supported. Different from a **while **loop, the do-while loop uses a boolean test executed at the end of the statement, so the do statement is always executed at least once.

```
def count = 5
def fact = 1
do {
    fact *= count--
} while(count > 1)
assert fact == 120
```


**<span style="color: #222222">for/for-in loop</span>**

*<span style="color: #222222">for / for-in </span>*<span style="color: #222222">loop</span><span style="color: #000000"> </span><span style="color: #000000">is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use the </span>*<span style="color: #000000">for</span>*<span style="color: #000000"> loop. </span><span style="color: #222222">In Groovy the </span>*<span style="color: #222222">for</span>*<span style="color: #222222"> loop is much simpler </span><span style="color: #222222">and works with any kind of array, collection, Map, etc.</span>

```groovy
// Normal for loop
def x = 0
for (i = 0; i < 5; i++) {
    x += i;
  }
x == 10 //returns true

// iterate over a range
def x = 0
for ( i in 0..9 ) {
    x += i
}
x == 45 //returns true

// iterate over an array
def array = (0..4).toArray()
x = 0
for ( i in array ) {
    x += i
}
x == 10 //returns true

//iterate over a list
def x = 0
def list = [10,12,13,14]; 
  for(j in list){
    x += j;
}
x == 49  //returns true
 
//iterate over a map
def x = 0
  def customers = [
    0 : "David",
    1 : "Elle",
    2 : "Peaches"
  ];

for(cust in customers){
    x += cust.key
  }
x ==  3 //returns true

//iterate over values of a Map
def x = ""
  def customers = [
    0 : "David",
    1 : "Elle",
    2 : "Peaches"
  ];

for(cust in customers){
    x += cust.value
  	x += ","
  }
x == "David,Elle,Peaches"  //returns true

// iterate over the characters in a string
def text = "abc"
def list = []
for (c in text) {
    list.add(c)
}
list == ["a", "b", "c"] //returns true
```

### Branching statements

<span style="color: #000000">The branching statements are the loop controlling statements. Break and Continue can be used to control the workflow in codes that run in an endless loop.</span>

`break`<span style="color: #000000">** statement**</span>** - **<span style="color: #000000">The </span>`break`<span style="color: #000000"> statement is used to alter the flow of control inside loops and switch statements, explained above.</span>

`continue`<span style="color: #000000">** statement - **</span><span style="color: #000000">The </span>`continue`<span style="color: #000000"> statement complements the break statement. Its use is restricted to while and for loops, explained above.</span>

`return`<span style="color: #000000">** statement - **</span><span style="color: #000000">The last line of a method in Groovy is automatically the </span>`return`<span style="color: #000000"> statement. For this reason, an explicit </span>`return`<span style="color: #000000"> statement can be left out.</span>