In Java, the ternary operator (also known as the conditional operator) is a shorthand way of writing an if
-else
statement. The ternary operator takes three operands: a condition, a value to be returned if the condition is true, and a value to be returned if the condition is false.
Here's an example of how to use the ternary operator in Java:
int x = 10; int y = 20; int max = (x > y) ? x : y;
In this example, the ternary operator compares the values of x
and y
and returns the maximum value. If the condition (x > y)
is true, the value of x
is returned. If the condition is false, the value of y
is returned.
The ternary operator can be used as a shorter alternative to an if
-else
statement:
int max; if (x > y) { max = x; } else { max = y; }
You can find more information about the ternary operator and how to use it in Java in the Java documentation.