问题
Hey, I have the following two lines of code:
result[i] = temp[i] + temp[i + 1] + " " + temp[i + 2];
i += 2;
I am wondering if this line of code would do the same:
result[i] = temp[i] + temp[i++] + " " + temp[i++];
Can I be sure, that EVERY VM would process the line from the left to the right? Thanks, Tobi
回答1:
From Java language 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.
It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.
回答2:
It should be
result[i] = temp[i] + temp[++i] + " " + temp[++i];
if I am not wrong, so that the indexes are computed after each incrementation. Apart from that it should work.
回答3:
Let's just try actually quoting the source.
Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
It looks like someone found a link to the spec as well.
回答4:
No it's not the same. When you put the ++ after i it implies that it is postfix, i.e. i will first be used and THEN incremented.
So:
result[i] = temp[i] + temp[i++] + " " + temp[i++];
would be the same as the below if i = 1:
result[1] = temp[1] + temp[1] + " " + temp[2];
and after this statement i would be sitting with value of 3.
For it to be the same as:
result[i] = temp[i] + temp[i + 1] + " " + temp[i + 2];
You should use the prefix increment operator, i.e:
result[i] = temp[i] + temp[++i] + " " + temp[++i];
回答5:
i++ will output the value and increment
++i will increment the value and output.
来源:https://stackoverflow.com/questions/4978900/java-multiple-increases-in-one-line-which-one-first