Ternary vs if in Java

Why is using ternary type wrong if used correctly?

//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);
}

      

+3


source to share


2 answers


Terminal conditional is not allowed as a stand-alone statement. Only certain expressions, such as assignment or method invocation, are allowed as a stand-alone operator.

The JLS classifies those expressions that are allowed as stand-alone expressions as StatementExpression

:

Purpose
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression



There are some obscure ways to use the trinity here:

// 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 them, they are really just curiosity. Easier to use if...else

.

+7


source


The main purpose of the ternary operator is to compress multiple lines if ... the condition is on one line. To improve the readability of your code. The ternary operator is also known as the conditional assignment operator, so here's if you don't assign a value. Therefore it gives error.

To make your code work with ternary operator, you can modify the code as shown below.



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

      

Best practice is to split this type of code into if ... else code block

0


source







All Articles