The ternary operator ?:
14 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)The ternary operator ?: picks one of two values using a condition. marks >= 35 ? "Pass" : "Fail" gives "Pass" when the condition is true and "Fail" when it is false.
How ?: works
A result card must show "Pass" or "Fail", but marks >= 35 gives only true or false.
Java checks the condition first: if it is true, the answer is the value after ?; if false, the value after :. It is called ternary because it has three parts.
Experiment
Pass mark
Slide marks across 35 and watch the answer switch.
- marks >= 35
- true
- result
- Pass
Picking a number with ?:
A cinema charges students Rs 100 and everyone else Rs 200. ?: picks between two numbers the same way it picks between two words.
Example · Ticket price and the bigger number
public class Ticket { public static void main(String[] args) { boolean isStudent = true; int fee = isStudent ? 100 : 200; System.out.println("Ticket: Rs " + fee); int a = 45; int b = 72; int bigger = a > b ? a : b; System.out.println("Bigger: " + bigger); }}Ticket: Rs 100 Bigger: 72
What this code does
- The condition can be a
booleanvariable.isStudentistrue, sofeegets 100. - It can also be a comparison:
a > bisfalse, sobiggergetsb, which is 72. This is a handy way to find the bigger of two numbers.
Both results need the same type
A shop label should say "In stock" or show 0, but one String variable cannot hold text one time and a number the next.
boolean isStudent = true;int marks = 40;int fee = isStudent ? 100 : 200; // both int: fineString r = marks >= 35 ? "Pass" : 0; // error: bad type in conditional expressionThe two results are called branches, and both need the same type.
Mixing int and double compiles but surprises you: isStudent ? 1 : 2.5 gives a double, so even the 1 comes out as 1.0.
Use ?: for a small choice between two values, and do not put one ?: inside another. When there is more to do, if-else (opens in a new tab) is clearer.
Next step
Check your understanding
8 quick questions