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

前端 未结 16 1754
轮回少年
轮回少年 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:02
    int count = isHere ? getHereCount(index) : getAwayCount(index);
    

    means :

    if (isHere) {
        count = getHereCount(index);
    } else {
        count = getAwayCount(index);
    }
    
    0 讨论(0)
  • 2020-11-21 06:05

    Its Ternary Operator(?:)

    The ternary operator is an operator that takes three arguments. The first 
    argument is a comparison argument, the second is the result upon a true 
    comparison, and the third is the result upon a false comparison.
    
    0 讨论(0)
  • 2020-11-21 06:06

    It's the conditional operator, and it's more than just a concise way of writing if statements.

    Since it is an expression that returns a value it can be used as part of other expressions.

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

    Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.

    Ternary Conditional Operator

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

    I happen to really like this operator, but the reader should be taken into consideration.

    You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.

    First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.

    Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:

    callMethodWhatever(Long + Expression + with + syntax) if conditional
    

    If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.

    The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.

    When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.

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

    Correct. It's called the ternary operator. Some also call it the conditional operator.

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