In pages like http://en.wikipedia.org/wiki/?: the ternary/conditional operator ?: seems to be used for conditional assignments. I tried to use it for method calling, like this:
(condition) ? doThis() : doThat();
Both methods return void. Java tells me it is not a statement.
So, I’m guessing I can’t do conditional method calling… or can I?
Think of ternary operators like a method in this case. Saying
a ? b : cis (for the intents and purposes you’re considering, see lasseespeholt’s comment) equivalent to calling the pseudocode method:which is why people can say things like
x = a ? b : c; it’s basically like sayingx = ternary(a, b, c). When you say(condition) ? doThis() : doThat(), you’re in effect saying:Look what happens if we try to substitute the methods for what they return
It doesn’t even make sense to consider it.
doThis()anddoThat()don’t return anything, becausevoidisn’t an instantiable type, so theternarymethod can’t return anything either, so Java doesn’t know what to do with your statement and complains.There are ways around this, but they’re all bad practice (you could modify your methods to have a return value but don’t do anything with what they return, you could create new methods that call your methods and then return null, etc.). You’re much better off just using an
ifstatement in this case.EDIT Furthermore, there’s an even bigger issue. Even if you were returning values, Java does not consider
a ? b : ca statement in any sense.