enhancedJack enhancedJack - 1 year ago 60
Java Question

Why can't I replace if statement with conditional operator (?:)?

I've been struggling to turn

private PlaneClass preferredClass;

if (preferredClass == PlaneClass.FIRST_CLASS)
preferredClass = PlaneClass.ECONOMY_CLASS;
preferredClass = PlaneClass.FIRST_CLASS;


preferredClass == PlaneClass.FIRST_CLASS ?
preferredClass = PlaneClass.ECONOMY_CLASS
: preferredClass = PlaneClass.FIRST_CLASS;

The if-statement compiles.
The conditional operator doesn't. (Error messages: 1. Type mismatch: cannot convert from PlaneClass to boolean 2. syntax error on token "=". And two other error...). Where did I go wrong?

Answer Source

The syntax is:

condition ? value1 : value2;


condition ? statement1 : statement2;

A ternary operator—such as the conditional operator—is an expression, not a statement. It doesn't evaluate expressions like an if statement does; it returns a value.

What you mean is:

preferredClass = (preferredClass == PlaneClass.FIRST_CLASS ? 
            PlaneClass.ECONOMY_CLASS : PlaneClass.FIRST_CLASS);