Computer Science
Explain Ternary operator with an example.
Java Operators
31 Likes
Answer
condition ? expression 1 : expression 2
Ternary operator evaluates the condition. If the condition is true then result of ternary operator is the value of expression 1. Otherwise the result is the value of expression 2.
Example:
boolean isLeapYear = true;
int febDays = isLeapYear ? 29 : 28;
Here, the ternary operator checks if the value of boolean variable isLeapYear
is true or false. As it is true, expression 1, which in this example is the value 29, is the result of the ternary operator. So, int variable febDays
becomes 29.
Answered By
18 Likes