What is the Java ?: operator called and what does it do?

前端 未结 16 1713
轮回少年
轮回少年 2020-11-21 05:27

I have been working with Java a couple of years, but up until recently I haven\'t run across this construct:

int count = isHere ? getHereCount(index) : getAw         


        
16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 06:24

    According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.

    The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

    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)).

    ConditionalExpression:
            ConditionalOrExpression
            ConditionalOrExpression ? Expression : ConditionalExpression
    

    The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.

    The first expression must be of type boolean or Boolean, or a compile-time error occurs.

提交回复
热议问题