Groovy Ternary Operator
Ternary Operator (?:
) simplifies conditional logic.
Supports nested conditions like (condition) ? A : (anotherCondition) ? B : C
.
Helps write shorter, cleaner Groovy code.
Reference
Groovy Operators Guide
🔗 https://groovy-lang.org/operators.htmlCovers ternary (
?:
), Elvis (?:
for null checks), and other Groovy-specific operators.Includes syntax and examples.
Groovy Style Guide - Ternary Operator Usage
🔗 https://groovy-lang.org/style-guide.htmlProvides best practices for writing concise ternary expressions.
Example
An employee receives a bonus based on their years of service:
If years of service ≥ 5, the bonus is 20% of salary.
Otherwise, the bonus is 10% of salary.
We will use the ternary operator (?:
) to determine the bonus.
def calculateBonus(double salary, int yearsOfService) {
return (yearsOfService >= 5) ? salary * 0.20 : salary * 0.10
}
// Example Calls
return calculateBonus(5000, 6) // Expected: 1000.0
return calculateBonus(5000, 3) // Expected: 500.0
Instructions
Task 1: Check Even or Odd
Write a function that returns "Even"
if the number is even, otherwise return "Odd"
.
def checkEvenOdd(int num) {
return /* Student's solution */
}
// Example Calls
return checkEvenOdd(4) // Expected: "Even"
return checkEvenOdd(7) // Expected: "Odd"
Task 2: Determine Age Group
Write a function that classifies a person as "Child"
(age < 13), "Teen"
(13-19), or "Adult"
(20+).
def getAgeGroup(int age) {
return /* Student's solution */
}
// Example Calls
return getAgeGroup(10) // Expected: "Child"
return getAgeGroup(15) // Expected: "Teen"
return getAgeGroup(25) // Expected: "Adult"
Task 3: Find Maximum of Two Numbers
Write a function that returns the larger of two numbers.
def findMax(int a, int b) {
return /* Student's solution */
}
// Example Calls
return findMax(10, 20) // Expected: 20
return findMax(50, 30) // Expected: 50
Task 4: Check Voting Eligibility
Write a function that returns "Eligible"
if age is 18 or above, otherwise "Not Eligible"
.
def canVote(int age) {
return /* Student's solution */
}
// Example Calls
return canVote(17) // Expected: "Not Eligible"
return canVote(18) // Expected: "Eligible"
return canVote(25) // Expected: "Eligible"
Task 5: Check Positive, Negative, or Zero
Write a function that returns "Positive"
, "Negative"
, or "Zero"
based on the input number.
def checkNumber(int num) {
return /* Student's solution */
}
// Example Calls
return checkNumber(10) // Expected: "Positive"
return checkNumber(-5) // Expected: "Negative"
return checkNumber(0) // Expected: "Zero"
Task 6: Check if a String is Empty or Not
Write a function that returns "Not Empty"
if the string has content, otherwise return "Empty"
.
def checkString(String str) {
return /* Student's solution */
}
// Example Calls
return checkString("Hello") // Expected: "Not Empty"
return checkString("") // Expected: "Empty"
Related content
Found an issue in documentation? Write to us.