|
Java has only one ternary operator ?:. It operates on three operands. It is also known as conditional operator as it executes expressions based on some condition. The condition and expressions to be performed are specified as its operands. The basic format of conditional operator is:
booleanExpression ? expression1 : expression2;
The booleanExpression specifies a condition. The expression1 is evaluated if the condition specified in booleanExpression is evaluated to true. If not then the expression2 is evaluated. Figure 9.9 shows the order in which the conditional operator is evaluated.
![]() |
Both the expressions return value. Based on the condition, one of them is executed. You can assign the returned value to a variable. Figure 9.10 illustrates the use of this operator to assign a value to variable result based on condition (if a is a greater-than c).
![]() |
Since the condition (a > c) is false, the expression2 (b-a) is evaluated and 1 is assigned to b. Note that expression1 is not executed at all. Therefore the value of b is 2 when the expression b-a is executed. You can write a simple if-else that behaves exactly as the conditional operator ?:. The following code rewrites the code example in figure 9.10 with equivalent if-else.
int a=1,b=2,c=3,result;
if(a > c)
result = ++b;
else
result = b-a;
This equivalent if-else performs exactly same as the conditional operator in figure 9.10. The only difference is that you can write much concise code with conditional operator.
|
|
The syntax of conditional operator is not very friendly to use and if at all you use it, it may not be very readable. You can make code concise with conditional operator but it is not a real advantage as the compiler optimizes the code anyway at the compile time. However, you need to know the syntax of this operator for the exam as well as to read code that is using it anyway. |
You can assign the result of ternary operation to a variable. However, this variable must have the same (or compatible) data type as that of the expressions specified in ternary operation. For example, if the expression in ternary operation are returning a boolean value, you must store it in a boolean variable.
int a=1,b=2,c=3;
boolean isGreatest = (a > c) ? (a > b) : false; // valid!
The expressions (a > b) and false, both return boolean value. Hence, the result of ternary operation is stored in a boolean variable isGreatest.