Java Ternary Operator - Complete Guide
Introduction to Ternary Operator
The ternary operator (also called the conditional operator) provides a compact alternative to writing simple if-else statements. It helps assign values or return results in a concise way.
It is the only operator in Java that takes three operands, making it especially useful for straightforward conditional assignments.
Ternary Operator Syntax and Usage
General syntax: `condition ? expression1 : expression2`
If the condition evaluates to true, `expression1` is returned; otherwise, `expression2` is returned.
public class TernaryOperator {
public static void main(String[] args) {
int number = 10;
// Basic ternary operator
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is " + result);
// Ternary vs if-else
int a = 5, b = 10;
int max;
// Using if-else
if (a > b) {
max = a;
} else {
max = b;
}
System.out.println("Max (if-else): " + max);
// Using ternary operator
max = (a > b) ? a : b;
System.out.println("Max (ternary): " + max);
// Nested ternary operators
int x = 10, y = 20, z = 15;
int largest = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
System.out.println("Largest number: " + largest);
// Ternary in print statements
int age = 17;
System.out.println("You are " + (age >= 18 ? "an adult" : "a minor"));
// Ternary with method calls
String input = "Hello";
String output = (input != null && !input.isEmpty())
? input.toUpperCase()
: "Default Value";
System.out.println("Output: " + output);
}
}
The number is Even Max (if-else): 10 Max (ternary): 10 Largest number: 20 You are a minor Output: HELLO
Best Practices and Limitations
The ternary operator should be used for clarity, not to complicate logic:
1. Use it for simple conditional assignments where readability improves.
2. Avoid deeply nested ternary expressions as they reduce readability.
3. Do not place expressions with side effects (like increments) inside ternary operators.
4. For multi-step logic, prefer traditional if-else statements for better clarity.
public class TernaryBestPractices {
public static void main(String[] args) {
// Simple and clear usage
int value = 15;
String category = (value > 10) ? "High" : "Low";
System.out.println("Category: " + category);
// Nested ternary (less readable)
int score = 85;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
System.out.println("Grade: " + grade);
// Equivalent if-else (more readable for complex cases)
String betterGrade;
if (score >= 90) {
betterGrade = "A";
} else if (score >= 80) {
betterGrade = "B";
} else if (score >= 70) {
betterGrade = "C";
} else if (score >= 60) {
betterGrade = "D";
} else {
betterGrade = "F";
}
System.out.println("Better Grade: " + betterGrade);
// Avoid side effects inside ternary expressions
int count = 0;
if (count > 0) {
count++;
} else {
count--;
}
System.out.println("Count: " + count);
}
}
Category: High Grade: B Better Grade: B Count: -1