The conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement in Java. It allows you to write a single line of code that performs a conditional test and returns one of two possible values, depending on the outcome of the test.
The syntax of the ternary operator is as follows:
condition ? value_if_true : value_if_false
Here, condition
is the expression that is tested, value_if_true
is the value that is returned if the condition is true, and value_if_false
is the value that is returned if the condition is false.
For example, consider the following code that uses an if-else statement to determine the minimum of two numbers:
int a = 10, b = 20;
int min;
if (a < b) {
min = a;
} else {
min = b;
}
This can be rewritten using the ternary operator as follows:
int a = 10, b = 20;
int min = (a < b) ? a : b;
In this case, the expression (a < b)
is evaluated. If it is true, the value of a
is assigned to min
. If it is false, the value of b
is assigned to min
.