简体   繁体   中英

questions on conditional operator in java

I hava read from Khalid Mugal and others that the conditional operator is right associative.

Can someone explain to me what this means and show me a simple example?

It is right-associative because it is specified as such in the Java Language Specs :

The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

The quote from the original spec provides an example (or at least something, that can be used to write a quick main based demo in Java)

Conditional Operator ?: is right associative because right side evaluates first

Explaniation A simple expression of conditional operator is

condition ? value if true : value if false

and an example is

boolean ? (10+20):(30+40)

in any case either true or false, its evaluate/calculate values on right side first then returns value according to condition

Further Explaination : It is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

Also consider Wiki defination

"The associativity (or fixity) of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses ."

Hopes that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM