| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Can the ternary operator be used instead of simple if-else statement?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
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 (? :):
|