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
- Start with n is 2
- Do this Is n positive?
- Result yes
int n = 2
if (n > 0) {
println("yes")
} else {
println("no")
}
yes
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.
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
int stock = 3
String status
if (stock == 0) {
status = 'sold out'
} else if (stock <= 5) {
status = 'order soon'
} else {
status = 'in stock'
}
println status
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.