Java Ternary Operator
Table of Contents + β
In the last lesson you learned about Java bitwise operators. Very often you just want to pick one of two values based on a condition, like βif the score is high, say Pass, else say Fail.β Java has a one-line tool for exactly this: the ternary operator.
π€ Why a one-line choice?
Often you just want one value or the other based on a true-or-false question. A full if-else for that is heavy. Here is a small choice written the long way.
int age = 20;String status;if (age >= 18) { status = "Adult";} else { status = "Minor";}System.out.println(status);This works fine. The output is below.
Output
AdultThat is the cost of the long form:
- Five lines just to pick between two words.
- You must declare
statusempty first, then fill it inside theif. - The variable sits blank for a moment, waiting.
The ternary operator does the same job in one clean line. It declares status and gives it the right value at the same time. No empty placeholder, no braces.
π§© The ternary syntax
The ternary operator uses a question mark and a colon. It is the only Java operator that takes three parts, which is why it is called βternaryβ (made of three). Here is the shape.
condition ? valueIfTrue : valueIfFalseHere is how Java works through it:
- It checks the
conditionfirst. That part must be true or false, likeage >= 18. - If true, the whole thing becomes
valueIfTrue(before the colon). - If false, the whole thing becomes
valueIfFalse(after the colon). - The
?asks the question, the:separates the two answers.
Here is the same age example as a ternary. One line instead of five.
int age = 20;String status = age >= 18 ? "Adult" : "Minor";System.out.println(status);age >= 18is true (age is 20), sostatusgets"Adult"(before the colon).- If
agewere under 18, the condition is false, sostatuswould get"Minor"instead. - Same result as the long
if-else, far shorter.
Output
Adultπ It returns a value, so it is an expression
This is the big idea that makes the ternary special:
- An
if-elseis a statement. It does something but does not stand for a value, soString s = if (...) ...is rejected. - The ternary is an expression. An expression produces a value, like
5,a + b, orage >= 18 ? "Adult" : "Minor". - So you can drop a ternary anywhere a value is allowed.
Because it hands back a value, you can use it in these spots:
- Assign it to a variable:
int max = a > b ? a : b; returnit from a method:return n % 2 == 0 ? "even" : "odd";- Put it inside a
print:System.out.println(x > 0 ? "positive" : "not positive");
π Turning an if-else into a ternary
Any simple two-way if-else that sets one variable can become a ternary, and back again. Here is the conversion rule:
- The
ifcondition becomes the part before the?. - The value from the
ifblock goes before the colon. - The value from the
elseblock goes after the colon.
This if-else decides a ticket price for a passenger.
int age = 10;double price;if (age < 12) { price = 5.0;} else { price = 10.0;}System.out.println(price);The age is 10, so the child price applies.
Output
5.0Now the same logic folded into a ternary. Same variable, same two values, one line.
int age = 10;double price = age < 12 ? 5.0 : 10.0;System.out.println(price);The condition age < 12 is true, so price becomes 5.0. Identical work, packed tighter.
Output
5.0π‘ More everyday examples
The ternary shines whenever you assign or print one of two values. Here are common patterns.
This one finds the larger of two numbers.
int a = 8;int b = 12;int max = a > b ? a : b;System.out.println("The larger value is " + max);a > b is false (8 is not greater than 12), so max gets b (after the colon). That gives 12.
Output
The larger value is 12Flip the comparison for the smaller one. Same pattern, < instead of >.
int a = 8;int b = 12;int min = a < b ? a : b;System.out.println("The smaller value is " + min);a < b is true, so min takes a (before the colon). That gives 8.
Output
The smaller value is 8This labels a number as even or odd. The % operator gives the remainder, so n % 2 is 0 when n divides evenly by two.
int n = 7;String label = n % 2 == 0 ? "even" : "odd";System.out.println(n + " is " + label);Seven leaves a remainder of 1, so n % 2 == 0 is false. The ternary hands back "odd".
Output
7 is oddYou can also drop a ternary inside a print, with no variable at all. Here we check an account balance.
double balance = 0;System.out.println(balance > 0 ? "In credit" : "Empty account");balance > 0 is false (the balance is exactly 0), so the ternary gives "Empty account".
Output
Empty accountOne more. A shop gives a discount only to members. The amount depends on one true-or-false flag.
boolean isMember = true;double discount = isMember ? 0.10 : 0.0;System.out.println("Discount rate: " + discount);isMember is true, so discount becomes 0.10. A non-member would land on 0.0 instead.
Output
Discount rate: 0.1Use it for values, not actions
The ternary is best when you are choosing a value, like which word or which number to use. If you need to do several actions in each branch, a normal if-else is clearer. Pick the tool that reads best out loud.
πͺ Nesting ternaries (and why deep nesting hurts)
What if you have three or more outcomes, like a grade letter (A, B, C, or F)? You can place a ternary inside another: the βfalseβ answer of the first becomes a new ternary. Here is a grade picker.
int score = 84;String grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";System.out.println("Grade: " + grade);Read it top to bottom. score >= 90 is false, so move on. score >= 80 is true, so it stops and returns "B". Java never checks the lower lines once it finds a match.
Output
Grade: BThat reads okay because each line is lined up neatly. But cram it onto one line and it turns into a wall of question marks and colons that no one can scan.
// β Avoid: one long nested line is painful to readString grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";Here is why deep nesting hurts:
- The ternary exists to make code shorter and clearer.
- Stack three or four and it does the opposite. It hides the logic.
- A reader has to stop and trace every
?and:by hand.
So for many outcomes, an if-else chain (or a switch, later) is the kinder choice.
// β
Clear for many outcomes: a plain if-else chainString grade;if (score >= 90) { grade = "A";} else if (score >= 80) { grade = "B";} else if (score >= 70) { grade = "C";} else { grade = "F";}Rule of thumb:
- One ternary: fine.
- Two stacked: only if they line up cleanly.
- Three or more: reach for
if-else.
π― Both branches must produce compatible types
A quiet rule that trips people up:
- The two values (before and after the colon) should be the same kind of type, or types Java can fit together.
- The whole ternary becomes one value, so Java needs to know that single valueβs type.
So this is asking for trouble. One branch hands back text, the other a number.
boolean flag = true;// β Mismatched types: one branch is text, the other is a numberString result = flag ? "yes" : 5;Java cannot store a plain 5 into a String, so it complains. Keep both branches the same kind of thing.
boolean flag = true;// β
Both branches are textString result = flag ? "yes" : "no";System.out.println(result);Output
yesThe same care applies to numbers:
- If one branch is
intand the otherdouble, Java widens the whole result todouble. - That is usually fine, but the result type may not be what you expected.
- When in doubt, make both branches the same type on purpose.
β οΈ Common Mistakes
A few ternary slip-ups to watch for.
-
Nesting too deeply. A ternary inside a ternary inside a ternary becomes a puzzle. When you have more than two outcomes, an
if-elsechain reads far better. Save the ternary for true two-way choices. -
Using it for side effects. The ternary is for choosing a value, not doing actions. Running method calls just for their effect is confusing and sometimes will not compile. If each branch needs to do work, use
if-else.
// β Don't use a ternary just to run actionsflag ? doThis() : doThat(); // awkward and often rejected
// β
Use if-else when you are performing actionsif (flag) { doThis();} else { doThat();}-
Mismatched value types. Both branches should produce compatible types. Text on one side and a number on the other causes an error.
-
Forgetting the colon. A ternary needs both the
?and the:. Leaving out the colon is a syntax error, and the program will not compile.
β Best Practices
Habits for using the ternary well.
- Use it for simple two-way choices. One condition, two possible values, one line. That is its sweet spot.
- Use it to set a variable.
String status = age >= 18 ? "Adult" : "Minor";is its most natural shape. You declare and assign in one go. - Keep both branches the same type. Text with text, number with number. That keeps the result predictable.
- Keep it readable. If the line gets long, or you start nesting, switch to
if-else. Short and clear beats clever and cramped. - Read it aloud. If you can say βif this, then that value, else that valueβ smoothly, the ternary fits. If you stumble, it probably belongs in an
if-else.
π§© What Youβve Learned
Nice, that wraps up operators. Letβs recap the ternary.
- β The ternary operator is a one-line way to choose between two values.
- β
Its shape is
condition ? valueIfTrue : valueIfFalse. The?asks the question, the:separates the two answers. - β It is an expression, so it returns a value. That means you can assign it, return it, or print it.
- β
It is great for setting one of two values, like
int max = a > b ? a : b;. - β Both branches must produce compatible types, like text with text or number with number.
- β
You can nest ternaries for many outcomes, but deep nesting hurts readability. Prefer
if-elsethen.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What is the correct syntax of the ternary operator?
Why: The shape is condition ? valueIfTrue : valueIfFalse. The ? asks the question and the : splits the answers.
- 2
Why can you write String s = a > b ? "big" : "small"; but not String s = if (a > b) ...;?
Why: The ternary is an expression, so it produces a value you can assign. An if-else is a statement, so it cannot stand in for a value.
- 3
What does int max = a > b ? a : b; do when a is 8 and b is 12?
Why: a > b is false (8 is not greater than 12), so max gets the value after the colon, which is b = 12.
- 4
Which is a poor use of the ternary operator?
Why: Deep nesting makes the ternary hard to read. For many outcomes, an if-else chain is clearer.
π Whatβs Next?
That completes operators. You can calculate, compare, and combine conditions. So far, though, you have been printing values without thinking much about how printing itself works. Next, letβs look closely at how Java sends text to the screen.