domi domi - 2 years ago 107
Java Question

"Do nothing" using ternary operator

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

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
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 Source

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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download