Ternary Operator
The ternary operator (?:) is Java’s only operator that takes three operands, which is where its name comes from. It is a compact, expression-based alternative to a simple if-else statement — instead of executing one of two blocks of code, it evaluates to one of two values.
Syntax
condition ? valueIfTrue : valueIfFalse
Java evaluates condition first. If it is true, the whole expression evaluates to valueIfTrue; if it is false, the whole expression evaluates to valueIfFalse. Exactly one of the two value expressions is ever evaluated, never both.
A Compact Alternative to if-else
Compare these two equivalent pieces of code:
Using if-else
String status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}Using the ternary operator
String status = (age >= 18) ? "adult" : "minor";
Both versions produce the same result, but the ternary version expresses “pick one of two values” in a single line, which reads naturally when the sole purpose of the if-else is to assign a value.
Worked Example: Finding the Maximum of Two Numbers
MaxFinder.java
public class MaxFinder {
public static void main(String[] args) {
int a = 15;
int b = 42;
int max = (a > b) ? a : b;
System.out.println("The larger number is: " + max);
}
}The larger number is: 42
Here, (a > b) is the condition. Since 15 > 42 is false, the expression evaluates to b, and 42 is assigned to max.
Nesting Ternary Operators
Because the ternary operator produces a value, you can nest one ternary expression inside another to check multiple conditions:
int score = 82;
String grade = (score >= 90) ? "A"
: (score >= 80) ? "B"
: (score >= 70) ? "C"
: "F";
System.out.println(grade); // BUse the ternary operator for simple, single-condition value selection — especially in assignments, return statements, and method arguments.
Avoid nesting more than one level deep; prefer if-else or switch once logic gets that complex.
Both branches of a ternary should generally produce compatible types, since the overall expression has a single type.