user1420042
user1420042

Reputation: 1709

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?

Upvotes: 2

Views: 6422

Answers (3)

Antimony
Antimony

Reputation: 39451

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.

Upvotes: 3

Nathan Hughes
Nathan Hughes

Reputation: 96385

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.

Upvotes: 14

Magnus
Magnus

Reputation: 11396

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.

Upvotes: 3

Related Questions