Groovy Control Structures: Detailed Explanation
Groovy supports various program control structures, including conditional statements and loops.
Here are some common program control structures in Groovy along with examples:
- if-else statement: Executes different code blocks based on conditions.
def age = 18
if (age >= 18) {
println("You are an adult")
} else {
println("You are a minor")
}
- switch statement: Executes different code blocks based on different values.
def grade = "B"
switch (grade) {
case "A":
println("Excellent")
break
case "B":
println("Good")
break
case "C":
println("Fair")
break
default:
println("Invalid grade")
}
- for loop statement: Iterates over data structures such as lists or arrays.
def list = [1, 2, 3, 4, 5]
for (item in list) {
println(item)
}
- while loop statement: Repeats a code block as long as a specific condition is met.
def i = 0
while (i < 5) {
println(i)
i++
}
- do-while loop statement: Executes a code block at least once, then repeats it if a specific condition is met.
def i = 0
do {
println(i)
i++
} while (i < 5)
- break statement: Exits the current loop.
def i = 0
while (i < 5) {
if (i == 3) {
break
}
println(i)
i++
}
- continue statement: Skips the remaining code in the current iteration and proceeds to the next loop cycle.
def list = [1, 2, 3, 4, 5]
for (item in list) {
if (item == 3) {
continue
}
println(item)
}
Please note that Groovy also supports nested control structures and other program control structures such as try-catch-finally statements.