Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 885
user1420042 Avatar asked Nov 30 '25 11:11

user1420042


2 Answers

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.

like image 98
Nathan Hughes Avatar answered Dec 03 '25 01:12

Nathan Hughes


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.

like image 28
Magnus Avatar answered Dec 03 '25 02:12

Magnus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!