The ternary operator is a form of syntactic sugar for
It is also known as the conditional operator, which is perhaps a more meaningful name because it evaluates conditions like
Provided that the operator is used with care, it can make code more concise without sacrificing readability.
This article requires you to have a solid understanding of how
if-statements work in Java.
The ternary operator evaluates a condition and chooses one of two branches to execute.
Like in many other programming languages,
: symbols are used to form it.
Other common names you might encounter that refer to the same concept are inline if, ternary if and the conditional operator.
The name ternary refers to the fact that the operator takes three operands.
condition is a boolean expression that evaluates to either
exprFalse are also expressions but they can evaluate to anything you want them to (except
If the condition is
true, the ternary operator evaluates
exprFalse is evaluated.
The ternary operator is an expression (like
price + 20 for example), which means that once executed, it has a value.
And that value needs to be further used, for example by assigning it to a variable or returning from a method, or the expression will not compile.
It’s worth mentioning that the operator is lazy in the sense that only the used expression is evaluated: The ternary operator will not evaluate the unused branch.
As you can see, the basic structure is very similar to an
else statement but it is condensed to a single line.
Let’s have a look at a concrete example.
It demonstrates how a simple
else statement can be replaced with a ternary operator.
price variable gets a value based on whether the user is a premium member or not.
As you can see, the ternary operator is succinct and in this case improves readability.
Since you can use it as an expression, oftentimes it enables you to remove multiple return statements in a method by replacing them with a single expression.
Can be replaced with
price method is considerably shorter and as legible as before.
Nesting Multiple Operators
Java allows to nest one conditional operator into another one. Be careful when doing that though. Nested conditional operators can hinder readability.
You’ve learned that the ternary operator allows you to shorten an
else statement to a single line
condition ? exprTrue : exprFalse.
If done wisely, it makes the code more concise and improves readability.
Fewer lines of code is not always better, though. It’s easy to overuse the ternary operator and make your code less readable. Use common sense and keep in mind that programs must be written for people to read, and only incidentally for machines to execute. A more readable way to express conditions, particularly if there are many of them, can be the switch statement.