Java separates some elements of your program into statements and expressions. A statement is an instruction to do something, and an expression is code that produces some value. You can write an expression and ignore the value (Math.sin(0);
), called an expression statement, but a statement on its own has no value and can't be made into an expression.
The conditional/ternary operator ?:
works only on expressions; that is, it's not a general flow-control tool like if
but can only be used to select between two alternate values. Since System.out.println
returns void (no value), it can only be called as a statement and thus can't be used as a ternary.
You can always use if
to select between entirely different statements (usually and preferably block statements); if you want to use the conditional operator with System.out.println
you must use it to select an expression to be passed to it as its argument:
System.out.println(condition ? "true" : "false"); // an expression of type String