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

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

    Conditional expressions are in a completely different style, with no explicit if in the statement.

    The syntax is: boolean-expression ? expression1 : expression2;

    The result of this conditional expression is

    expression1 if boolean-expression is true;

    otherwise the result is expression2.

    Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression: max = (num1 > num2) ? num1 : num2;

    Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.

    cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

提交回复
热议问题