Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ternary operator with empty clause

This question is more for my curiosity than anything else.

I often employ Java's ternary operator to write shorter code. I have been wondering, however, whether it is possible to use it if one of the if or else conditions are empty. In more details:

int x = some_function();
if (x > 0)
    x--;
else
    x++;

can be written as x = (x > 0) ? x-1 : x+1;

But is it possible to write if (x > 0) x-1; as a ternary expression with an empty else clause?

like image 757
Chthonic Project Avatar asked Oct 30 '13 15:10

Chthonic Project


People also ask

How do you do nothing in ternary operator?

A ternary operator doesn't have a do nothing option for either the true or false path since the entire ternary command returns a value and so both paths must set a value. The “do nothing” value will depend on what value you want the ternary operator to return to indicate “do nothing”.

What is ?: In Java?

The ternary conditional operator ?: allows us to define expressions in Java. It's a condensed form of the if-else statement that also returns a value.

Can we write ternary operator without else?

You cannot use ternary without else, but you can use Java 8 Optional class: Optional.

Can ternary operator be used without assignment?

Nope you cannot do that.


1 Answers

But is it possible to write if (x > 0) x--; as a ternary expression with an empty else clause?

No, the conditional operator requires three operands. If you wanted, you could do this:

x = (x > 0) ? x - 1 : x;

...but (subjectively) I think clarity suffers.

like image 129
T.J. Crowder Avatar answered Sep 25 '22 02:09

T.J. Crowder