The ternary operator op1 ? op2 : op3 works just like a condensed if-else statement. If op1 is true, returns op2; otherwise, returns op3. Can we use the tenery operator anywhere that applies to an if-else statement?
Click below links to know more
The answer is no. Under some circumstances, we have to use the if-else statement. The following sample code is taken from Conditional Operator.com and a compile-time error will occurs:
class Program { static void doSomethingX() { } static void doSomethingY() { } pubic static void main(String[] args) { int x; ... //the following line causes compile-time error System.out.println((x==5)?doSomethingX():doSomethingY()); } }
Note that it is a compile-time error for either the second or the third operand expression to be an invocation of avoid
method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of avoid
method could appear.
Comments
Post a Comment