The ternary operator "?:" earns its name because it's the only operator to take three operands. It is a conditional operator that provides a shorter syntax for the if..then..else statement. The first operand is a boolean expression; if the expression is true then the value of the second operand is returned otherwise the value of the third operand is returned:
boolean expression ? value1 : value2
For example, the following if..then..else statement
boolean isHappy = true;
String mood = "";
if (isHappy == true)
{
mood = "I'm Happy!";
}
else
{
mood = "I'm Sad!";
}
can be reduced to one line using the ternary operator:
boolean isHappy = true;
String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!";
Generally the code is easier to read when the if..then..else statement is written in full but sometimes the ternary operator can be a handy syntax shortcut.


that one line should be more concise:
String mood = isHappy ? “I’m Happy!” : “I’m Sad!”;
you don’t have to compare a boolean with true or false, as evaluating it as an expression yields true or false already.
Yep, you’re right. And, if you look at the condition in the if statement, that too can be reduced to being just
if (isHappy)
I think having the expressions written so that beginners can see how the logic is being evaluated can make them a little easier to understand. But, I’ll add a note to the end of the glossary entry with the concise version too.
until you need to debug that sht
Debugging it is not so difficult if you do understand it. Making things clear is important but being concise does produce faster and better code.
Roark, more concise code does not run any faster. You’re writing in a high level language like Java so your code will be readable. The byte-compiled if/else and ternary will ultimately run the same, no matter how many ‘lines of code’ you use.
Great explanation….thanks a lot
Of course, the ternary won’t be faster because it’s code is shorter.
Readability depends on the complexity of the surrounding code. I like the ternary, because it avoids the curly brace jungle. The line structure can be split to 2 rows, so it stay readable.
I never understood the complaint that the ternary operator was harder to debug…
debugging a one line assignment is far simpler to me.
Ternary operations may seem nice to the oh-so-clever original author but these are horrid for the poor sap stuck maintaining your undocumented creation. Eighty percent of the cost of any software is it’s maintenance so clarity & comments really count in the long run! If you’ve just got to use them, please add parentheses around each condition and a descriptive comment for the next programmer.
And for crying out loud, don’t nest ternary operators.
Awesome explanation! The ternary operator has confused me a bit, but I now understand it completely thanks to your article here.
Cheers!