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

前端 未结 16 1760
轮回少年
轮回少年 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:23

    This construct is called Ternary Operator in Computer Science and Programing techniques.
    And Wikipedia suggest the following explanation:

    In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.

    Not only in Java, this syntax is available within PHP, Objective-C too.

    In the following link it gives the following explanation, which is quiet good to understand it:

    A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

    In Perl/PHP it works as:
    boolean_condition ? true_value : false_value

    In C/C++ it works as:
    logical expression ? action for true : action for false

    This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.

    We can simplify the If-Else blocks with this Ternary operator for one code statement line.
    For Example:

    if ( car.isStarted() ) {
         car.goForward();
    } else {
         car.startTheEngine();
    }
    

    Might be equal to the following:

    ( car.isStarted() ) ? car.goForward() : car.startTheEngine();
    

    So if we refer to your statement:

    int count = isHere ? getHereCount(index) : getAwayCount(index);
    

    It is actually the 100% equivalent of the following If-Else block:

    int count;
    if (isHere) {
        count = getHereCount(index);
    } else {
        count = getAwayCount(index);
    }
    

    That's it!
    Hope this was helpful to somebody!
    Cheers!

提交回复
热议问题