Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
Can the ternary operator be used instead of simple if-else statement?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: Can the ternary operator (op1 ? op2 : op3) be used instead of simple if-else statement?

Can the ternary operator (op1 ? op2 : op3) be used instead of simple if-else statement?


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?

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;
    ...
    System.out.println((x==5)?doSomethingX():doSomethingY()); //compile-time error
   
  }
}

In 15.25 Conditional Operator (? :):

Note that it is a compile-time error for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.

 


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help