简体   繁体   中英

Is there a conditional operator without the else part in Java?

I know that that you can use something like this in Java:

(a > b) ? a : b;

Is there something similar just without the else part?

It's an expression, not a statement, which means it always evaluates to something. If there wasn't an "else part" there would be nothing for the expression to evaluate to if the test was false. So, no, there's nothing similar without the else.

The thing I like about using the conditional operator is that you can assign something like

foo =  a > b ? c : d;

and reading it you know foo got something assigned to it, regardless of whether the test was true. So it provides you with a way to indicate that a value is assigned that depends on some test.

Groovy has some similar operators:

?: , the Elvis operator, assigns the value on the right as a default if the expression on the left is null.

?. , the safe-null operator, evaluates to null if the left side evaluates to null. This is handy for cases where you have a chain of possibly-null things, like foo?.bar?.baz , where you would rather not blow up with an NPE if something is null but would rather not type out all the null checks.

No there isn't. It wouldn't make sense.

?: is the ternary comparison operator - an expression. If there was no else statement, what would the value of the expression be? C# has a shorthand version ?? but that's just syntactical sugar and Java doesn't have anything like that anyway.

I'm guessing that you're using it to assign a value to a var, which I'll call "c", and the idea is you only want to assign the value when the if statement is true. The normal way would be:

if(a > b) c = a;

But if you really want to use the ternary syntax you could write:

c = a > b ? a : c;

Note that the ternary parens are optional so I've omitted them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM