Groovy Expressions vs. Statements

In Groovy, an expression is a statement that computes and returns a value; it can contain variables, constants, operators, method invocations, and other expressions. In contrast, a statement executes a specific operation that may not return any value.

Here are some examples of expressions in Groovy:

// Arithmetic expression
def a = 10
def b = 5
def c = a + b // c = 15

// Comparison expression
def x = 10
def y = 5
def result = x > y // result = true

// Logical expression
def isAdult = true
def hasLicense = false
def canDrive = isAdult && hasLicense // canDrive = false

// Method invocation expression
def list = [1, 2, 3, 4, 5]
def size = list.size() // size = 5

Here are some examples of statements in Groovy:

// if-else statement
def age = 18
if (age >= 18) {
    println("You are an adult")
} else {
    println("You are a minor")
}

// for loop statement
def list = [1, 2, 3, 4, 5]
for (item in list) {
    println(item)
}

// while loop statement
def i = 0
while (i < 5) {
    println(i)
    i++
}

// method invocation statement
def list = [1, 2, 3, 4, 5]
list.add(6)
println(list) // Output: [1, 2, 3, 4, 5, 6]

Please note that in Groovy, most statements can be treated as expressions because they all return a value. For instance, the return value of an if-else statement is the return value of the code block executed when the condition is met, while the return value of a method invocation statement is the return value of the invoked method.