Java: Ternary with no return. (For method calling)

No, you can't. But what's the point of this over an if-else statement? Are you really trying to save 7 characters?

if (name.isChecked()) {
    name.setChecked(true);
} else {
    name.setChecked(false);
}

or if you prefer bad style:

if (name.isChecked()) name.setChecked(true); else name.setChecked(false);

Never mind the fact that you can just do (in this case):

name.setChecked(name.isChecked());

The point of the ternary or "conditional" operator is to introduce conditionals into an expression. In other words, this:

int max = a > b ? a : b;

is meant to be shorthand for this:

int max;
if ( a > b ) {
    max = a;
} else {
    max = b;
}

If there is no value being produced, the conditional operator is not a shortcut.


I was wondering if it was possible to do a ternary operation but without returning anything.

No it is not possible:

  1. The 2nd and 3rd operands are required to be non-void expressions; i.e. they must produce some actual value.

    "It is a compile-time error for either the second or the third operand expression to be an invocation of a void method." - JLS 15.25.

  2. A ternary expression is an expression, and cannot be used as a statement.

    "Certain kinds of expressions may be used as statements by following them with semicolons." ... and the ternary expression is not one of those kinds - JLS 14.8.

If you really, really want to use a ternary expression but not use the value of the expression, then the simplest thing is to assign the value to a dummy variable, and add an annotation to suppress the warning about the variable not being used.

But a better idea is to use a plain if statement.

If it's not possible in Java is it possible in other languages, if so which ones apply?

I'm a bit rusty, but I believe that C, C++ and Perl all allow arbitrary expressions to be used in places where their values are not used.


Sometimes, you can use ternary operation on method arguments to solve your request.

name.setChecked(name.isChecked() ? true : false);

By the way, the best solution for your problem is

name.setChecked(name.isChecked());