Why can’t I use the ternary ? operator to select between two function calls?

Not every expression is a statement. Use an if statement here. See Section 14.8 Expression Statements in the Java SE 7 Java Language Specification.

Certain kinds of expressions may be used as statements by following
them with semicolons.

ExpressionStatement:
    StatementExpression ;

StatementExpression:
    Assignment
    PreIncrementExpression
    PreDecrementExpression
    PostIncrementExpression
    PostDecrementExpression
    MethodInvocation
    ClassInstanceCreationExpression

Examples of expression statement for each of the above:

x = y;
++x;
--x
x++;
x--;
fn(); // Or donkey.fn();, etc.
new Donkey(this);

What you can’t do is:

b ? f() : g();
f() + g();

However, if you’re dead set on obfuscating your code, I guess you could write:

fn(a == 0 ? vertShip(board) : horizShip(board));
(a == 0 ? vertShip(board) : horizShip(board)).fn();

(I think. I don’t have a compiler to hand and wouldn’t usually write such code.)

Leave a Comment