The ternary conditional isn't allowed as a standalone statement. Only certain expressions are allowed as a standalone statement, like an assignment or a method call.
The JLS classifies those expressions which are allowed as a standalone statement as StatementExpression
:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
There are a couple of obscure ways to use the ternary here anyway:
// statement is an assignment
boolean ignored =
Character.isDigit(...) ?
digitArrayList.add(myDto) : charArrayList.add(myDto);
// statement is a method invocation
(Character.isDigit(...) ? digitArrayList : charArrayList)
.add(myDto);
But I don't recommend using those, they are really just a curiosity. It's more clear to just use the if...else
.