Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Groovy - Control Structures: If-Else, Switch

6. Control Structures: If-Else, Switch

Control structures are used to control the flow of a program based on specific conditions. In Groovy, you can use 'if-else' statements for basic conditional branching and 'switch' statements for more complex, multi-case branching.

1. If-Else Statements:

The 'if-else' statement allows you to execute different code blocks based on whether a given condition is true or false.

Syntax:
if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}
 
Example:
def age = 25

if (age >= 18) {
    println("You are an adult.")
} else {
    println("You are a minor.")
}
 

In this example, the code checks if the 'age' variable is greater than or equal to 18. If the condition is true, it prints "You are an adult." Otherwise, it prints "You are a minor."

2. Switch Statements:

The 'switch' statement allows you to select one code block to execute from several alternatives based on the value of an expression.

Syntax:
switch (expression) {
    case value1:
        // Code to execute if expression equals value1
        break
    case value2:
        // Code to execute if expression equals value2
        break
    // ...
    default:
        // Code to execute if no case matches
}
 
Example:
def dayOfWeek = "Tuesday"

switch (dayOfWeek) {
    case "Monday":
        println("It's the start of the week.")
        break
    case "Tuesday", "Wednesday":
        println("It's the middle of the week.")
        break
    default:
        println("It's not the start or middle of the week.")
}
 

In this example, the 'switch'statement checks the value of  'dayOfWeek' and executes the code block associated with the matching case. If no case matches, it executes the code in the 'default' block.

3. Nested If-Else:

You can also use nested 'if-else' statements to handle more complex conditions.

Example:
def score = 85

if (score >= 90) {
    println("Grade: A")
} else if (score >= 80) {
    println("Grade: B")
} else if (score >= 70) {
    println("Grade: C")
} else {
    println("Grade: D")
}
 

In this example, the code assigns a grade based on the 'score' variable using a series of nested 'if-else' statements.

Control structures like 'if-else' and 'switch' are fundamental for implementing conditional logic in your Groovy programs. They allow you to make decisions and execute specific code blocks based on the conditions you define. Understanding and using these constructs effectively is key to writing structured and functional code.