Use of Java Ternary Operator with ==

Viewed 62

Not able to understand the issue with the below code block.

numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]);

Getting error: not a statement.

2 Answers

You cannot use a ternary operator in a statement context. It is only allowed as an expression. You have two options:

  1. Use an if statement:

    if (numArray[i] % 2 == 1) {
        oddList.add(numArray[i]);
    } else {
        evenList.add(numArray[i]);
    }
    
  2. Restructure the ternary operator (does not work in general, but removes some duplication in this case):

    (numArray[i] % 2 == 1 ? oddList : evenList).add(numArray[i]);
    

In addition to previous comment. Java program consists of statements. In you case numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]); is part of ConditionalExpression. ConditionalExpression must be part same statement for example Assigment or ReturnStatement.

Thus you can use this, because List.add() returns boolean value:

  1. Assigment boolean b = numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]);

  2. Return

    return numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]);

  3. Another statement with boolean value...

Related