A ternary operator is a conditional operator that takes three operands:
a condition followed by a question mark (?
), a result expression to evaluate if the condition is true, followed by a colon (:
), and another result expression to evaluate if the condition is false.
The syntax of the ternary operator is:
condition ? expression1 : expression2
Here's how it works:
If the condition evaluates to true,
expression1
is executed.If the condition evaluates to false,
expression2
is executed.Ternary operators are often used as shortcuts for simple conditional statements, providing a more concise way to express conditional logic, especially in cases where the if-else statement would be repetitive or verbose. They are particularly useful when assigning values based on conditions or when returning values from functions based on conditions.
-
int max = num1 > num2 ? num1 : num2;
is the ternary operator.It checks the condition
num1 > num2
. If this condition is true, it assigns the value ofnum1
tomax
; otherwise, it assigns the value ofnum2
.So, if
num1
is greater thannum2
,max
will be assigned the value ofnum1
; otherwise, it will be assigned the value ofnum2
.Finally, it prints the result using
print("The greatest number is $max");
.