Java Ternary Operators
www.igifaedit.com
The Java ternary operator is a shorthand notation for an if-else statement. It is also known as the conditional operator. The ternary operator takes three operands: a boolean expression, a value to be returned if the expression is true, and a value to be returned if the expression is false.
The syntax of the ternary operator is as follows:
boolean_expression ? value_if_true : value_if_false;
Here is an example that demonstrates the use of the ternary operator:
int a = 10; int b = 20; int max = (a > b) ? a : b; System.out.println("The maximum value is " + max);
In this example, the ternary operator (a > b) ? a : b
is used to determine the maximum value between a
and b
. If the boolean expression (a > b)
is true, the value of a
is returned; otherwise, the value of b
is returned. The result is assigned to the variable max
, which is then printed to the console.