JAVA calling a method using a ternary operator

Trae Moore picture Trae Moore · Sep 28, 2012 · Viewed 13.2k times · Source

I am trying to use ? to decide which method i want to call, but i do not need to assign a variable. My question: Is there a way to use the ternary operator with out assigning a variable?

(something i dont need) = (x == 1)? doThisMethod():doThatMethod()

instead of

if(x == 1) {
    doThisMethod()
} else {
    doThatMethod()
}

Answer

Kevin DiTraglia picture Kevin DiTraglia · Sep 28, 2012

This will not work, as it is not the intended use of the ternary operator.

If you really want it to be 1 line, you can write:

if (x==1) doThisMethod(); else doThatMethod();