Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: multiple ++-increases in one line. Which one first?

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

like image 819
Tobi Avatar asked Mar 11 '26 03:03

Tobi


2 Answers

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.

like image 107
adamax Avatar answered Mar 12 '26 17:03

adamax


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.

like image 40
Dunaril Avatar answered Mar 12 '26 16:03

Dunaril