Search code examples
javaternary

JAVA calling a method using a ternary operator


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()
}

Solution

  • 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();