The ternary operator is the operator that works on three operands and used to make single line conditional statements. It is also known as the short-hand of if-else statement. We can use it in Java to validate an expression.
The syntax of the ternary operator in Java.
variable = expression ? statement1 : statement2;
It uses two symbols ? (question mark) and : (colon) to construct a conditional statement.
The expression is a boolean expression that returns a boolean value either true or false.
Based on the return value either the first statement or the second statement is evaluated.
Let's understand it with a simple example.
In this example, we used the ternary operators to find the greater value between two integers. Usually, programmers use if-else statements to perform these conditional operations but with the help of ternary operators, we can do the same. See how the code is compact.
/*
* Code example of ternary operator in Java
*/
public class JExercise {
public static void main(String[] args) {
int a = 10;
int b = 12;
String str = (b>a)?"a is greater":"b is greater";
System.out.println(str);
}
}
Output:
a is greater
This example is an if-else version of the above code. You can think of it as.
/*
* Code example of ternary operator in Java
*/
public class JExercise {
public static void main(String[] args) {
int a = 10;
int b = 12;
String str = "";
if(b>a) {
str = "a is greater";
}
else { str = "b is greater";
}
System.out.println(str);
}
}
Output:
a is greater
Like, nested if-else statements, we can create nested ternary operators as well. See, in this example, we used nested ternary operators to find a greater value.
/*
* Code example of nested ternary operator in Java
*/
public class JExercise {
public static void main(String[] args) {
int a = 8;
String str = (a > 10) ? "Number is greater than 10" :
(a > 5) ? "Number is greater than 5" : "Number is less than equal to 5";
System.out.println(str);
}
}
Output:
Number is greater than 5