3

I have the following piece of code. This is how I understand it.

In the first case, the ternary operator returns the value of y because x=4 and the print statement prints 5, as expected.

In the 2nd case, the ternary operator first assigns the value of y to x and then returns that value. Again, it prints 5, as expected.

In the 3rd case, the ternary operator has x=y to the left of the : and x=z to the right of the :. I would expect this to behave much like the 2nd case. However, this statement does not even compile.

Any help in understanding this will be much appreciated.

public class Test {

    public static void main(String[] args) {
        int x = 4;
        int y = 5;
        int z = -1;

        x = (x == 4) ? y : z;        // compiles and runs fine
        System.out.println(x + " " + y + " " + z);

        x = (x == 4) ? x = y : z;    // compiles and runs fine
        System.out.println(x + " " + y + " " + z);

        x = (x == 4) ? x = y : x = z;  // Does not compile
        System.out.println(x + " " + y + " " + z);
    }
}
1
  • 1
    Either x = (x==4)?(x=y):(x=z); or x = (x==4)?x=y:(x=z); does. Commented Jan 27, 2015 at 2:22

2 Answers 2

5

Assignment has lower precedence than a ternary expression, so this expression:

(x==4)?x=y:x = z;

can be thought of as:

((x==4)?x=y:x) = z;

Which obviously won't compile because you can't assign a value to something that isn't a variable.

Sign up to request clarification or add additional context in comments.

Comments

2

Add parenthesis to control the order of evaluation

x = (x == 4) ? (x = y) : (x = z); // Does compile.

Note the above is equivalent to

if (x == 4) {
    x = (x = y);
} else {
    x = (x = z);
}

Which will (as a side effect) of assigning a value to x assign the value assigned to x to x. In other words, your ternary is equivalent to

x = (x == 4) ? y : z;

or

if (x == 4) {
   x = y;
} else {
   x = z;
}

The ternary is specified in JLS-15.25. Conditional Operator ? :.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.