No you can't. The ternary operator b ? x : y
(where b, x and y are statements) evaluates to something.
b
must evaluate to a boolean
x
must evaluate to a value (either a primitive or an object)
y
must evaluate to a value of the same type as x
- the statement as a whole evaluates to a value of the same type as
x
and y
I suppose you could imagine a language in which when x
and y
do not evaluate to a value, then the statement b ? x : y
does not evaluate to a value either. In that language, r = b ? x : y
would be an illegal statement when r = x
or r = y
were illegal statements.
But Java is not that language. In Java the ternary operator always has to return something (even if you don't use the result), and therefore so must its second two operands.
It's not normal to call the ternary operator "the short if statement".
In your use case, use if
and else
.