domi domi - 6 months ago 13
Java Question

"Do nothing" using ternary operator

I want to use the ternary operator like this - checking only the

true
part of the statement:

foo() ? bar() : /* Do nothing */;


Is it possible to exclude the logic of the "else" part of this statement? I tried using
return;
but the compiler gives the error. Basically all I want to achieve is a statement using ternary operator which would look like this:

foo() ? bar();


Is this achievable?

Answer

The ternary operator is usually used to immediately assign a value.

String a = bar() ? foo() : null;

For your usecase, you can simply use an if construct:

if (foo())
    bar();
Comments