Groovy — Comparison and short-circuit operators
Groovy's && operator stops evaluating as soon as a condition is false. An explicit range check lets an application reject indices outside its domain.
A simple example
Test two conditions
- Start with n is 2
- Do this Greater than 0 and less than 3?
- Result yes
int n = 2
if (n > 0 && n < 3) {
println("yes")
}
yes
Operator examples
| Operation | Expression | Result |
|---|---|---|
| Integer division | 7.intdiv(2) |
3 |
| Decimal division | 7 / 2 |
3.5 |
| Remainder | 7 % 2 |
1 |
| Comparison | 5 >= 5 |
true |
| Value equality | 3 == 4 |
false |
| Logical conjunction | true && false |
false |
Guard an indexed lookup
Combine comparisons with a short-circuiting logical operator. Check that a zero-based index is within bounds before reading the element at that index. Groovy collections support negative subscripts. The first comparison deliberately excludes those relative positions because this lookup accepts only zero-based external indices.
A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.
Run the example
Use Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
def stock = [2, 5]
for (int i in [-1, 1, 2]) {
boolean take = i >= 0 && i < stock.size() && stock[i] >= 5
println(take ? 'take' : 'skip')
}
skip take skip
Only index 1 is in bounds in the three trial lookups. Its value is exactly the threshold of 5, so it passes the inclusive comparison.
Try it yourself
Try index 0, then change its value from 2 to 5. How does its classification change?
Check your answer
Index 0 is valid in both cases. It changes from skip to take when its value reaches 5.