The ternary operator
Choose between two values in a single expression, and know when it hurts readability.
Open this lesson in the learning hubKey points
condition ? whenTrue : whenFalseis an expression, so it produces a value you can assign or return.- Only the branch that is needed runs, exactly like
&&. The other side is never evaluated. - Both branches must have compatible types; the result type is worked out at compile time.
- Chain it for a small ladder, but stop at two or three levels. Beyond that use
ifor a switch expression. - An
intbranch beside anullbranch boxes toInteger; unboxing that into anintthrows. - Perfect for defaults and singular/plural text. Poor for anything with a side effect.
Example
public class Main {
static String grade(int score) {
return score >= 90 ? "A"
: score >= 75 ? "B"
: score >= 60 ? "C"
: "F";
}
public static void main(String[] args) {
for (int s : new int[]{95, 80, 61, 42}) {
System.out.println(s + " -> " + grade(s));
}
String name = null;
System.out.println("null-safe label: " + (name != null ? name : "anonymous"));
int a = 7, b = 12;
System.out.println("max without Math.max: " + (a > b ? a : b));
int count = 1;
System.out.println(count + (count == 1 ? " file" : " files") + " copied");
Integer boxed = args.length > 0 ? args.length : null;
System.out.println("mixing int and null boxes to Integer: " + boxed);
System.out.println("assigning that to an int would throw NullPointerException");
}
}
Use a ternary when you need a value, an if when you need a statement.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.