Java Ternary Operator
The ternary operator in Java, also known as the conditional operator, provides a compact and elegant way to perform conditional evaluations. It allows developers to replace simple if-else statements with a single line of code, making programs cleaner and more readable.
The ternary operator is especially useful when assigning a value to a variable based on a condition. It evaluates a boolean expression, and depending on whether the result is true or false, it returns one of two possible values.
Syntax of the Ternary Operator
variable = (condition) ? expression_if_true : expression_if_false;
Explanation:
- condition → A boolean expression that evaluates to true or false.
- expression_if_true → Value (or statement) returned if the condition is true.
- expression_if_false → Value (or statement) returned if the condition is false.
Example 1: Check Even or Odd Number
public class EvenOddCheck {
public static void main(String[] args) {
int number = 7;
String result = (number % 2 == 0) ? “Even” : “Odd”;
System.out.println(“The number is ” + result);
}
}
Output:
The number is Odd
Explanation:
The condition (number % 2 == 0) checks if the number is divisible by 2.
- If true, it assigns “Even” to the variable result.
- If false, it assigns “Odd”.
This single line replaces a longer if-else structure effectively.
Example 2: Check Voting Eligibility
public class VotingEligibility {
public static void main(String[] args) {
int age = 20;
String message = (age >= 18) ? “Eligible to vote” : “Not eligible to vote”;
System.out.println(message);
}
}
Output:
Eligible to vote
Explanation:
The condition (age >= 18) is evaluated. Since the person’s age is 20, it returns the first expression, “Eligible to vote”.
Example 3: Find the Maximum of Two Numbers
public class MaxNumber {
public static void main(String[] args) {
int a = 15, b = 25;
int max = (a > b) ? a : b;
System.out.println(“The maximum number is ” + max);
}
}
Output:
The maximum number is 25
Explanation:
Here, the ternary operator checks if a > b. Since the condition is false, it assigns b to the variable max.
Example 4: Nested Ternary Operator
You can use multiple ternary operators together (called nesting) for more complex conditions. However, they should be used carefully for readability.
public class GradeCalculator {
public static void main(String[] args) {
int marks = 85;
String grade = (marks >= 90) ? “A+” :
(marks >= 80) ? “A” :
(marks >= 70) ? “B” :
(marks >= 60) ? “C” : “F”;
System.out.println(“Grade: ” + grade);
}
}
Output:
Grade: A
Explanation:
This nested ternary operator evaluates conditions in sequence until one returns true. The first true condition assigns its corresponding value to the variable grade.
Example 5: Using Ternary Operator with Methods
The ternary operator can also be used to control method outputs dynamically.
public class TemperatureCheck {
public static void main(String[] args) {
int temperature = 32;
String weather = (temperature > 30) ? “Hot” : “Cool”;
displayWeather(weather);
}
static void displayWeather(String type) {
System.out.println(“The weather is ” + type);
}
}
Output:
The weather is Hot
Explanation:
Here, the ternary operator decides the value of weather before calling the displayWeather() method.
Key Points to Remember
- The ternary operator is the only operator in Java that takes three operands.
- It improves code readability and compactness when used for simple conditions.
- Use parentheses for clarity, especially when nesting ternary operators.
- Avoid overusing nested ternary expressions, as they can make code harder to read.
- It’s ideal for conditional assignments, method returns, and inline decisions.
Comparison: if-else vs Ternary Operator
| Feature | if-else Statement | Ternary Operator (?:) |
|---|---|---|
| Syntax | Multi-line structure | Single-line expression |
| Return Type | Doesn’t return a value directly | Returns a value |
| Readability | Easy to understand for complex logic | Best for simple conditions |
| Use Case | When multiple conditions or actions are required | When assigning value based on a condition |
Conclusion
The Java ternary operator ( ?: ) is a concise and powerful alternative to if-else statements. It enhances code readability and reduces verbosity, especially when you just need to make quick conditional decisions. However, it’s best suited for simple conditions — for complex logic, sticking with if-else statements maintains better clarity and maintainability.
By mastering the ternary operator, you can write cleaner, shorter, and more efficient Java code that performs just as effectively as its longer counterpart.