Joe - 4 months ago 17

Java Question

Why does the Ternary operator (last line) give a compiler error?

`public static void main(String[] args){`

int x =0;

x=((x/y<3)?(x+=y):(x*=y));

x=(x/y<3?(x+=y):(x*=y));

x=(x/y<3?x+=y:(x*=y));

x=x/y<3?x+=y:(x*=y);

x=x/y<3?x+=y:x*=y; //compiler error

}

Answer

Reading the following article and its examples: http://alvinalexander.com/java/edu/pj/pj010018

I suspect the issues lies in the fact that the operator expects only a single thing to follow the colon. So it sees an "x", and then sees a *= and has no idea what to do with it. The previous examples worked as what's inside the parenthesis is evaluated first (into a single variable) and thus fits the syntax that a ternary expects.

To be more specific, a ternary operator is an if-else statement baked into one, used often to save on space when the conditions are simple assignments of values.

```
if(x/y < 3) {
x +=y;
} else
{
x *= y;
}
```

Is how the ternary will break down. Looking at the JLS the following definition for the "? :" operator.

```
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
```

As such, in his code, the x+=y is valid as it is an expression, however, the latter part cannot be an expression and that is the source of the error. More specifically, the *=y breaks it. The reason it worked with (x*=y) is that due to ORDER OF PRECEDENCE (for the commentator below) given to the () which convert it into a valid format.

Source (Stackoverflow)

Comments