3

Why using ternary like this is incorrect where as using if is correct?

//Error when using as ternary
Character.isDigit(myDto.getNameStr().charAt(0)) ? digitArrayList.add(myDto) : charArrayList.add(myDto);

//OK when used as if ... else
char c = myDto.getNameStr().charAt(0);
if(Character.isDigit(c)) {
  digitArrayList.add(myDto);
} else {
  charArrayList.add(myDto);
}
αƞjiβ
  • 3,056
  • 14
  • 58
  • 95
  • Not sure about this, but Character is a wrapper class while char is a primitive type (See: [char vs. Character](http://stackoverflow.com/questions/24823420/what-is-the-difference-between-char-and-character-in-java) ). This might be a problem while using a ternary operator. – hamena314 May 19 '15 at 14:18
  • What´s your compiler error? – SomeJavaGuy May 19 '15 at 14:22

2 Answers2

7

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.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
0

The fundamental purpose of the ternary operator is to compress multiple lines if..else condition into single line. So that it increases the readability of the code. The ternary operator is also known as conditional assignment operator, so here if you are not assigning the value. So it gives the error.

To make your code work with ternary operator, you can modify the code like below

boolean result =  Character.isDigit(myDto.getNameStr().charAt(0)) ? digitArrayList.add(myDto) : charArrayList.add(myDto);

The best practice is to divide this kind of code into if...else code block

Kartik Jajal
  • 732
  • 4
  • 10
  • 16