Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Ternary operator syntax [duplicate]

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);
    }
}
like image 692
user3516726 Avatar asked Jul 06 '26 14:07

user3516726


1 Answers

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.

like image 182
August Avatar answered Jul 08 '26 16:07

August



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!