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

前端 未结 16 1756
轮回少年
轮回少年 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.

    0 讨论(0)
  • 2020-11-21 06:25
    condition ? truth : false;
    

    If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.

    It is called the Conditional Operator and it is a type of Ternary Operation.

    0 讨论(0)
  • 2020-11-21 06:26

    You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:

    String s = mayBeNull?.toString() ?: "null";
    

    It would be especially convenient where auto-unboxing takes place.

    Integer ival = ...;  // may be null
    int i = ival ?: -1;  // no NPE from unboxing
    

    It has been selected for further consideration under JDK 7's "Project Coin."

    0 讨论(0)
  • 2020-11-21 06:27

    Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.

    e.g.:

    public class Foo {
        final double    value;
    
        public Foo(boolean positive, double value) {
            this.value = positive ? value : -value;
        }
    }
    

    Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.

    0 讨论(0)
提交回复
热议问题