Java

Ternary Operator Examples in Java3 min read

The ternary conditional operator ?: used to define expressions in Java. This is a condensed form of the if-else statement that also returns a value.

In this tutorial, we will see how to use the ternary conditional operator. We’ll start with its syntax and then explore its use.




Syntax:
The ternary operator ?: in Java is the only operator that accepts three operands:

The first operand must be a Boolean expression, the second and third operands can be any expression that returns a value. The ternary operator returns instruction1 as an output if the first operand evaluates to true, otherwise instruction2.

Example:
Let’s look at the following code:

In the code above, we assigned a value to str based on the conditional evaluation of n. We can make this code more readable and clearer by easily replacing the if-else statement with a ternary condition:

 

Ternary Operator in Java with Multiple Conditions

You can replace multiple lines of code with a single line of code using the ternary operator. This makes your code more readable. For example, you can replace the following code:

with:

The use of the ternary operator made the code more difficult to understand in this case. Use the ternary operator only when the resulting instruction is short. This makes the code more concise and much more readable.

 

Ternary Operator Examples

Example 1:

Output:

Example 2:

It’s possible for us to nest our ternary operator to any number of levels of our choice. So the construct:

is valid in Java. To improve the readability of the above code, we can use braces (), wherever necessary:

Howeverplease note that it’s not recommended to use such deeply nested ternary constructs in the real world. This is so as it makes the code less readable and difficult to maintain.

 

Leave a Comment