views:

101

answers:

2

I am debugging code that has in it expr1 & expr2 where expr1 has a side effect that affects expr2 evaluation result. I suspect that expr2 gets evaluated before expr1, since JLS guarantees left-to-right evaluation for &&, but not necessarily for &. I also suspect that change of evaluation order may be a result of optimization performed by HotSpot (we're running Java 6u20). Do you know if HotSpot can make such an optimization? Better yet, provide any pointers to documentation that either support or eliminate the suspicion. Thanks in advance.

EDIT: Thanks for those suggesting to rewrite the code so it's both correct and readable - you're right, but I already did, so it's not what I am looking for. Unfortunately it is hard to test the change, which is why I'm asking the question here.

+6  A: 

The evaluation order is well-defined in the specification:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

The HotSpot optimizer should not make an optimization that results in expr2 being evaluated before expr1 if this changes the result. If it does this it is a bug.

Note also it says:

It is recommended that code not rely crucially on this specification.

Your code could be rewritten more clearly as follows:

int a = expr1;
int b = expr2;
int result = a & b;
Mark Byers
+1  A: 

JLS 3rd edition section 15.7 talks about evaluation order from left to right but asks not to rely on it crucially (except for short circuit ones)

naikus