icn icn - 4 months ago 69
Java Question

ternary error: not a statement

I am confused why this is invalid in Java

(4 > 5) ? System.out.print("no") : System.out.print("yes");

It gave
error: not a statement
error. Why?


The ? ternary operator can only be used for values, not entire statements. It only returns a value, but it is not a statement in and of itself.

Try something like this instead:

System.out.println((4 < 5) ? "no" : "yes");