2

Can someone tell me why this use of the ternary operator is incorrect? Operands 2 and 3 return a boolean.

public class Something {
...
private static final double REFERENCE_FRAME_MID_X = 0;
private static final double REFERENCE_FRAME_MID_Y = 0;

private boolean findInsideOrOutsideGeneralEllipse(Point2D destCirclePos) {
    List<Boolean> returnValue = new ArrayList<>();
    Point2D referenceFrameCenter = new Point2D.Double(REFERENCE_FRAME_MID_X, REFERENCE_FRAME_MID_Y);
    Ellipse2D insideAreaEllipse2D = getEllipse2D(referenceFrameCenter.getX(), referenceFrameCenter.getY(),
                                                    destCirclePos.distance(referenceFrameCenter));

    // doesn't work
    insideAreaEllipse2D.contains(destCirclePos) ? returnValue.add(true) : returnValue.add(false);

    // works
    if (insideAreaEllipse2D.contains(destCirclePos)) {
        returnValue.add(true);
    } else {
        returnValue.add(false);
    }
}
...
}
9
  • 14
    you just want, returnValue.add(insideAreaEllipse2D.contains(destCirclePos)); Commented Sep 25, 2013 at 16:30
  • 1
    @nachokk I know it can be done that way, but I'd like to understand exactly why that is a compile-time error... Commented Sep 25, 2013 at 16:32
  • 4
    conditional operator does not exist to conditionally execute the expressions, but rather to conditionally return the (non-void) result of one of the expressions. Commented Sep 25, 2013 at 16:33
  • 2
    ternary operator must be used for assignment, otherwise you will get a compiler error. Commented Sep 25, 2013 at 16:34
  • 1
    What do you mean by "doesn't work"? The result of add is not the added value, but a boolean indicating whether or not the collection changed. The value of the expression will always be true, since the empty collection has a value added to it (either true or false). Commented Sep 25, 2013 at 16:34

2 Answers 2

10

Usage of Java ternary operation condition should looks like

result = testCondition ? value1 : value2

it's java-language specification.

Equality, Relational, and Conditional Operators

In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result

Sign up to request clarification or add additional context in comments.

7 Comments

I can't speak as to why you got downvoted, but there's no requirement that the result of a ternary expression be used as the right hand side of an assignment. condition ? val1 : val2 is an expression, and while it can't be used as a statement, there are lots of places you can use expressions, not just assignments. E.g., you could System.out.println( condition ? val1 : val2 );.
@JoshuaTaylor your code is equivalent to String s = condition ? val1 : val2; System.out.println(s);. It's the same that I said
@JoshuaTaylor note that you're already passing the result of condition ? val1 : val2 into a temporary variable that will be used in System.out.println( ... ). Try just having condition ? val1 : val2; with nothing on the left side. If you make it work, let us know to email James Gosling about this :).
@LuiggiMendoza. Joshua is talking about the places where you can use conditional operator. And it's not only in assignment context. The usage of ?: as argument to method, is not an assignment context, but a method invocation context.
@LuiggiMendoza I'm aware that the conditional expression isn't a statement. My point is that an expression can be used in other places than an assignment. Rohit Jain's answer quotes the specification about the grammar, and makes this clearer.
|
5

From JLS - Conditional Operator:

In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.

Grammar of expression statements from JLS - 14.8:

Certain kinds of expressions may be used as statements by following them with semicolons:

ExpressionStatement:
      StatementExpression ;

StatementExpression:
       Assignment
       PreIncrementExpression
       PreDecrementExpression
       PostIncrementExpression
       PostDecrementExpression
       MethodInvocation
       ClassInstanceCreationExpression

An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.

Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements.

Now the way you are using the conditional operator is not a valid expression statement, as inferred from it's grammar. And hence you get the compiler error. You have to use it in any of the above mentioned context.

6 Comments

I have explicitly pointed out that returnvalue.add() returns a boolean.
@deinocheirus The point isn't that the types of the expressions aren't compatible, but that the ternary operator expression (the conditional expression) isn't a statement, but an expression, and in your code it appears in a place where a statement is expected.
@deinocheirus Yes, but your code still isn't a StatementExpression.
@JoshuaTaylor he edited his answer to the point my comment no longer makes sense.
@Axel the same thing :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.