Javatpoint Logo
Javatpoint Logo

Ternary Operator Java

In Java, the ternary operator is a type of Java conditional operator. In this section, we will discuss the ternary operator in Java with proper examples.

The meaning of ternary is composed of three parts. The ternary operator (? :) consists of three operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the variable. It is the only conditional operator that accepts three operands. It can be used instead of the if-else statement. It makes the code much more easy, readable, and shorter.

Note: Every code using an if-else statement cannot be replaced with a ternary operator.

Syntax:

The above statement states that if the condition returns true, expression1 gets executed, else the expression2 gets executed and the final result stored in a variable.

Ternary Operator Java

Let's understand the ternary operator through the flowchart.

Ternary Operator Java

Example of Ternary Operator

TernaryOperatorExample.java

Output

Value of y is: 90
Value of y is: 61

Let's see another example that evaluates the largest of three numbers using the ternary operator.

LargestNumberExample.java

Output

The largest number is: 89

In the above program, we have taken three variables x, y, and z having the values 69, 89, and 79, respectively. The expression (x > y) ? (x > z ? x : z) : (y > z ? y : z) evaluates the largest number among three numbers and store the final result in the variable largestNumber. Let's understand the execution order of the expression.

Ternary Operator Java

First, it checks the expression (x > y). If it returns true the expression (x > z ? x : z) gets executed, else the expression (y > z ? y : z) gets executed.

When the expression (x > z ? x : z) gets executed, it further checks the condition x > z. If the condition returns true the value of x is returned, else the value of z is returned.

When the expression (y > z ? y : z) gets executed it further checks the condition y > z. If the condition returns true the value of y is returned, else the value of z is returned.

Therefore, we get the largest of three numbers using the ternary operator.


Next TopicJava Architecture




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA