0

I am trying to figure out how to use operators ? : instead if else block

My case is below:

if (boolean variable) {
void1(); }
else {
void2();
}

is it possible to do this by that way:

boolean variable ? void1() : void2();

I was looking for an answer but I cannot find it with boolean and call void method

chee
  • 21
  • 4
  • The ternary operator is not a replacement for if-else statements. It is used for assignments and doesn't work with void methods. – OH GOD SPIDERS Jul 13 '18 at 09:10
  • No, you can't put methods returning void into this kind of construction. Just use `if` and `else`. – Dawood ibn Kareem Jul 13 '18 at 09:10
  • 1
    See the difference between expressions and statements in Java : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html – Alex M Jul 13 '18 at 09:16

1 Answers1

-2

This will not work, as it is not the intended use of the ternary operator.Ternary operators will be used for assignments.

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

if (boolean variable) void1(); else void2();
VelNaga
  • 3,593
  • 6
  • 48
  • 82