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

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

    Not exactly correct, to be precise:

    1. if isHere is true, the result of getHereCount() is returned
    2. otheriwse the result of getAwayCount() is returned

    That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.

    Also, it's not exactly syntactically equivalent to the if-else version. For example:

    String str1,str2,str3,str4;
    boolean check;
    //...
    return str1 + (check ? str2 : str3) + str4;
    

    If coded with if-else will always result in more bytecode.

提交回复
热议问题