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.

Leave a Comment