The syntax of the ternary operator
The ternary operator is a shorthand way of writing if-else statements. The syntax of the ternary operator is as follows:
variable = (condition) ? expression1 : expression2;
Where condition
is the boolean expression that is evaluated, expression1
is the value assigned to variable
if condition
is true
, and expression2
is the value assigned to variable
if condition
is false
.
Let's see an example:
int num1 = 50;
int num2 = 100;
int result;
result = (num1 > num2) ? num1 : num2;
System.out.println(result);
Output:
100
In the example above, if num1
is greater than num2
, the value of result
becomes num1
, otherwise, the value of result
becomes num2
.