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