Ternary Operator in Java With Examples

Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions. In this tutorial, we will learn a basic overview of the ternary operator and its use in Java with the help of examples.


In Java, a ternary operator can be used to replace the if-else statement in certain situations. It is a type of Java conditional operator. It is the only conditional operator that takes three operands. It is a one-liner replacement for the if-else statement and is used a lot in Java programming. We can use this operator in place of if-else conditions or even in switch conditions using nested ternary operators. It used to make the code much more easy, readable, and shorter.

Switch Case

Java Ternary Operator Syntax :

java
(condition) ? expression1 : expression2;

First, the condition is evaluated. If it is true then expression1 is executed, else expression2 is executed.



Ternary Operator Example To find the maximum of 2 numbers :

java
// Example program for ternary operator.

import java.io.*;
public class largestnumber
{
public static void main(String[] args)
{
int X, Y;
X = 10;
Y = (X < 1) ? 20: 30;
System.out.println("Value of Y is : " + y);
y = (x >= 5) ? 50: 100;
System.out.println("Value of Y is: " + y);

}
}

Output :

Value of Y is : 30 Value of Y is : 50




Nested Ternary Operator in Java:

java
// To find greater number
int max, X, Y, Z;
max = (X > Y ? (X > Z ? X : Z) : (Y > Z ? Y : Z));

Java Nested Ternary Operator Example

java
// Java program to find the largest number among 3 numbers using ternary operator.

import java.io.*;
public class largestnumber
{
public static void main(String[] args)
{
int X = 10;
int Y = 50;
int Z = 20;
int largestNum = (X > Y ? (X > Z ? X : Z) : (Y > Z ? Y : Z));
System.out.println("The largest numbers : " + largestNum);

}
}

Output :

The largest numbers : 50