Seshadri R :
When I attempted to compile the following Java program:
public class MyClass
{
static int f1() { return 10; }
static int f2() { return 20; }
public static void main(String args[])
{
int x = 10;
(x <= 10) ? f1() : f2();
}
}
I got the error:
/MyClass.java:9: error: not a statement
(x <= 10) ? f1() : f2();
^
Java language definition talks about statements as one of assignment, increment/decrement, method invocation or object creation. My erroneous "statement" involves method invocation and should, therefore work. In fact, if I have a single statement like:
f1();
the compiler compiles the program sans any whimper. Similarly, if I change the final line to:
int y = (x <= 10) ? f1() : f2();
then too, everything is hunky-dory.
As a final piece of info, neither C nor C++ bats an eyelid on:
(x <= 10) ? f1() : f2();
Maurice Perry :
The ternary operator is used in expressions. For statements, you can use an if statement. That's how the syntax is defined. Period.