The ternary operator is a conditional operator in Java that is used to evaluate a boolean expression and return a value based on the outcome. It is often used as a shorthand way to write a simple if-else statement.
The syntax for the ternary operator is:
expression ? value if true : value if false
For example, consider the following code:
int x = 10; int y = 20; int max = x > y ? x : y;
In this example, the boolean expression
x > y is evaluated, and if it is true, the value of
x is returned as the value of
max. If it is false, the value of
y is returned as the value of
The ternary operator can be useful in situations where you need to perform a simple action based on a boolean condition, but you don’t want to write a full if-else statement. It can also be used to assign values to variables based on a condition. For example, the following code assigns a value to the
status variable based on the value of the
boolean isOnline = true; String status = isOnline ? "online" : "offline";
It is important to note that the ternary operator has lower precedence than other operators, so it is often necessary to use parentheses to ensure the correct order of operations. For example:
int x = 10; int y = 20; int max = (x > y) ? x : y;
Overall, the ternary operator is a useful tool for evaluating boolean expressions and performing simple actions based on the outcome. It can help you write concise and readable code in certain situations.