Ternary Operator in Java

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Video Tutorial

Ternary Operator

Overview

Ternary operator in Java is used as a replacement of if-then-else statement. It simulates this behavior - If expression 1 is true, variable = expression2 else variable = expression3. It is the only operator in Java that takes three arguments.

Scope

This article aims to:

  • Help understand learn how to use Ternary operator in Java with examples.
  • Explain the situations where it is wise to use Ternary operator in Java and where it is necessary to avoid them.

Introduction to Ternary Operator in Java

Operators in Java are symbols that instruct the compiler to perform a specific operation. Just like other operators like Arithmetic, Bitwise, Unary etc, Ternary Operator adds up to the list of operators available in Java.

  • If statement is too much code

We usually write conditional statements in our codes every now and then, as they play an important role in deciding some specific path of the workflow or often decide between multiple actions based on the condition.

Ternary operator allows us to translate multiple lines of code of an ‘if-else’ block into a single line. As a clean code developer, you might always question, if it’s a one liner if-else, is it readable? Yes it’s readable and structured more than an if-else block. Let’s see how it really does that with its syntax.

Syntax of Ternary Operator in Java

Variable = Condition ? Expression1 : Expression2

Condition: It represents the condition that is written in an if statement.

Expression1: This expression will be stored in the Variable if the condition turns out to be true.

Expression2: This expression will be stored in the Variable if the condition turns out to be false.

Variable: It stores the value returned by either expression.

Let us discuss it with the help of an example.

Example of Ternary Operator in Java

Output:

The above piece of code can be reduced drastically to just one line using the Ternary operator in Java:

Output:

Why is it called a “Ternary” Operator?

Ternary means composed of three parts. The name clearly justifies the operation it performs, as the statement is divided into three parts, conditional expression and the two different expressions.

Chained Operations or Nested Conditions

Chained operations are nested conditions in a ternary operation. We can achieve nested if-else in a ternary operation too.

Let’s consider two different examples with:

1. Basic chaining of if-else blocks.

2. Nested chaining of if-else blocks.

Basic Chaining of if-else blocks

For Basic Chaining of if else blocks, let’s consider an example where we have multiple lowercase letter and if the input matches the lowercase letter, it must assign its corresponding uppercase letter to the variable:

Example:

Output:

The above code snippet can be efficiently written as the following:

Output:

If you observe carefully, we’re using the expression (when the condition is false) as the next else if in the ternary operation. It’s called a chain operation as it’s a chain of conditions integrated with the false part of each ternary operation. Hence, creating a chain of ternary operations.

Nested Chaining of if-else blocks

Now, let’s consider an example for nested chaining of if else blocks. Let’s consider an example of a Drink Vending Machine that asks for two inputs. First input is for the amount and second input is for the drink you want to select for the same amount.

In the code snippet below, you can observe that code has become a spaghetti code as there are too many paths and directions in a single piece of code, hence reducing the readability of the code.

But, will writing a ternary chain operation for the same enhance the code cleanliness and the readability?

That’s not really the case, and here we’ll understand when do we really need to use ternary operation and where do “if else” blocks actually make sense!

Output:

So the above piece of code (if-else implementation) definitely has at least 5 times the lines of code as the below snippet (Ternary Operation). But is the ternary operation even readable? Won’t it take some time for one to understand what’s the basic purpose of this code when compared to the above snippet?

Only in cases like these, Ternary operations can and should be avoided, as they might hinder the code readability and quality. If there turns out to be any bug in the ternary operation, it’ll be difficult for a developer to debug.

Output:

When to Use a Ternary operator in Java?

  • Well, the Ternary operator in Java is definitely a better choice when it comes to writing conditional statements as it’s a shorthand property of an if else implementation.
  • But as the complexity of the conditions increase, it becomes hard to implement ternary operation, and if you write one, then it becomes relatively difficult for one to read it and hence troubleshooting incase of any bug in the statement is harder.
  • Also, it is important to store value in a variable in a ternary operation as each expression in the operator returns a value. Storing it in the variable becomes mandatory. Hence, when the conditional statement is supposed to change a specific variable or is supposed to return a specific type of data, ternary operator should be your go-to operation.

Conclusion

  • Ternary operator in Java is a shorthand implementation of conditional statements that significantly improves the code readability and quality.
  • Ternary operator in Java involves three expressions, hence the name.
  • A Ternary operator in Java handles the following behavior - if condition is true, variable = expression1 else expression2 in a single line.
  • It is important to realise when to use a ternary operator over if-else, as if-else also serve their purpose in multiple scenarios like nested conditions.