Control flow statements in Groovy are used to control the flow of execution in a program. They allow you to execute different blocks of code depending on certain conditions or to repeat a block of code multiple times. Here are the most commonly used control flow statements in Groovy:
1. If-else statements: If-else statements allow you to execute a block of code if a condition is true, and another block of code if the condition is false. Here’s an example:
def age = 20
if (age >= 18) {
println("You are an adult.")
} else {
println("You are a minor.")
}
2. Switch statements: Switch statements allow you to execute different blocks of code depending on the value of a variable or expression. Here’s an example:
def dayOfWeek = 3
switch (dayOfWeek) {
case 1:
println("Monday")
break
case 2:
println("Tuesday")
break
case 3:
println("Wednesday")
break
case 4:
println("Thursday")
break
case 5:
println("Friday")
break
default:
println("Weekend")
}
3. For loops: For loops allow you to repeat a block of code a fixed number of times. Here’s an example:
def sum = 0
for (i in 1..10) {
sum += i
}
println("The sum of the numbers 1 to 10 is $sum.")
4. While loops: While loops allow you to repeat a block of code while a certain condition is true. Here’s an example:
def i = 1
while (i <= 10) {
println("The value of i is $i.")
i++
}
5. Do-while loops: Do-while loops are similar to while loops, but the block of code is executed at least once before the condition is checked. Here's an example:
def i = 1
do {
println("The value of i is $i.")
i++
} while (i <= 10)
6. Break statements: Break statements allow you to exit a loop prematurely. Here's an example:
for (i in 1..10) {
if (i == 5) {
break
}
println("The value of i is $i.")
}
7. Continue statements: Continue statements allow you to skip to the next iteration of a loop. Here's an example:
for (i in 1..10) {
if (i % 2 == 0) {
continue
}
println("The value of i is $i.")
}
These are the basic control flow statements in Groovy. By using these statements, you cancontrol the flow of execution in your programs and make them more flexible and powerful.