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

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

提交回复
热议问题