A ternary operator is a conditional operator that takes three operands. It is used to simplify code that involves a simple conditional expression.
The syntax of the ternary operator is as follows:
(condition) ? (if true) : (if false)
Here, ‘condition‘ is the Boolean expression that is evaluated. If the expression is ‘true‘, the operator returns the ‘if true‘ value; otherwise, it returns the ‘if false‘ value.
For example, consider the following code that determines whether a number is even or odd:
int num = 10;
if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
The above code can be simplified using the ternary operator as follows:
int num = 10;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
In this case, the ‘condition‘ is ‘num
Ternary operators can also be nested, allowing for more complex conditional expressions. For example:
int num = 10;
String result = (num > 0) ? ((num % 2 == 0) ? "Positive even" : "Positive odd") : "Negative";
System.out.println(result);
In this example, the nested ternary operator first checks if ‘num‘ is positive or negative. If positive, it then checks if it is even or odd. If negative, it simply returns ‘"Negative"`.
In summary, ternary operators are used to simplify conditional expressions in programming by allowing for a more concise syntax. They are especially useful in cases where there is a simple true/false decision to be made.