Lesson contents

Groovy — Conditions with if and else

Groovy evaluates if and else if conditions in order. The first matching block handles the value, and a final else supplies the remaining outcome.

A simple example

Follow one branch

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
Lesson.groovy
int n = 2
if (n > 0) {
    println("yes")
} else {
    println("no")
}
Output
yes
Advertisements

Classify a stock level

The branches assign a String before println uses it. Test for zero explicitly. Groovy truth would also treat some other kinds of values as false in a more general expression.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.

Run the example

Groovy 4 on the JVM. Run these commands from the directory containing the example.

groovy Lesson.groovy
Lesson.groovy
int stock = 3
String status
if (stock == 0) {
    status = 'sold out'
} else if (stock <= 5) {
    status = 'order soon'
} else {
    status = 'in stock'
}
println status
Output
order soon

The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.

Try it yourself

Try the boundary values 0, 5, and 6.

Check your answer

They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.

Groovy language documentation

Related tags

  • Groovy
  • conditions
  • branching
  • comparison