FAQ

Java

JSP

Servlet


Advertisement



Can the ternary operator 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;
...
//the following line causes compile-time error
System.out.println((x==5)?doSomethingX():doSomethingY());

}
}

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.


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

  |   |