2

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();
Seshadri R
  • 1,192
  • 14
  • 24
  • 6
    "Involves" is not the same as "is". Your "statement" is a `?:` operator expression. An expression is not a valid statement in Java (i.e. it is none of the four you listed). What C and C++ do or don't do is not relevant. – Amadan Jul 05 '19 at 05:19

1 Answers1

3

The ternary operator is used in expressions. For statements, you can use an if statement. That's how the syntax is defined. Period.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • The compiler error message is ambiguous. Whether it means that I have not provided any qualified Java statement, or the operator **?:** cannot be used in a statement. I will wait for a couple of days, before accepting your answer. – Seshadri R Jul 05 '19 at 06:06
  • @SeshadriR the message is very clear: the compiler is expecting a statement, but it has found something else. – Maurice Perry Jul 05 '19 at 06:20