简体   繁体   English

关于java中条件运算符的问题

[英]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 : 它是右关联的,因为它在Java语言规范中被指定为:

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)). 条件运算符在语法上是右关联的(它从右到左分组),因此a?b:c?d:e?f:g表示与?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) 原始规范中的引用提供了一个示例(或者至少可以用于在Java中编写基于main的快速演示的东西)

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)). 进一步的解释它在语法上是右关联的(它从右到左分组),因此a?b:c?d:e?f:g表示与?b相同:(c?d:(e? F:G))。

Also consider Wiki defination 还要考虑Wiki定义

"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 希望有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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