Ternary Operator
At a cinema ticket counter: "Under 12? Child ticket. Otherwise, adult ticket." That's one question and two possible answers. Java has an operator built for exactly this: the ternary operator, condition ? valueIfTrue : valueIfFalse. It's called ternary because it takes three parts, and it lets you pick between two values in a single expression.
How It Works
public class Ticket {
public static void main(String[] args) {
int age = 9;
String type = age < 12 ? "Child" : "Adult";
int price = age < 12 ? 120 : 250;
System.out.println(type + " ticket: Rs. " + price);
}
}Child ticket: Rs. 120How it works
- Line 4 checks
age < 12. It'struefor 9, so the whole expression becomes"Child", the value after?. - Line 5 asks the same question and picks
120. - If
agewere 30, the values after:would be chosen:"Adult"and250.
Try it yourself: change age to 12. Which ticket do you get, and why?
Ternary vs if-else
The ternary on line 4 does the same job as this if-else:
String type;
if (age < 12) {
type = "Child";
} else {
type = "Adult";
}| Use the ternary when | Use if-else when |
|---|---|
| You're choosing between two values | You're choosing between two actions (printing, saving, calling methods) |
| Both values are short | Either branch needs several lines |
| It fits comfortably on one line | There are more than two cases |
You'll learn if-else properly in "Java If-Else Statements".
Result Type
Both sides of a ternary should have the same type, or types Java can combine. When they're different numeric types, the usual promotion rules apply:
public class Mixed {
public static void main(String[] args) {
boolean member = true;
double discount = member ? 10 : 2.5;
System.out.println("Discount: " + discount + "%");
}
}Discount: 10.0%The two possible values are 10 (an int) and 2.5 (a double), so the result is a double, and 10 prints as 10.0.
Common Mistakes
Using a ternary for actions. age < 12 ? System.out.println("Child") : System.out.println("Adult"); doesn't compile, because println returns nothing. Use if-else for actions.
Forgetting that only one side runs. Only the chosen value is evaluated, so a method call on the other side never happens. That's usually what you want, but it surprises people while debugging.
Getting the order wrong. It's always condition ? ifTrue : ifFalse. A quick check: the true value sits next to the question mark.
Practice
- Easy: Use a ternary to print "Pass" when marks are 35 or more, and "Fail" otherwise.
- Harder: Use a ternary to set the delivery charge to 0 when the order total is Rs. 499 or more, and Rs. 40 otherwise. Print the final amount for totals of 450 and 520.
Key Takeaways
Was this tutorial helpful?