Java ternary operator syntax

See English answers > terminal operator, syntax error when using assignment

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 second case, the ternary operator first assigns the value of y to x, and then returns the value Again, it prints as expected 5

In the third case, the ternary operators are x = y on the left: and x = Z on the right: I hope this is very similar to the second case However, this statement is not even compiled

Any help in understanding this will be greatly 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);
    }
}

Solution

The priority of assignment is lower than that of ternary expression, so this expression:

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

It can be considered as:

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

Obviously, you cannot compile because you cannot assign values to content that is not a variable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>