Anton
Anton

Reputation: 53

increments order in java

Why in java this code outputs 1:

int bracketsTest = 0;
int resultBrackets = 1 + bracketsTest + bracketsTest++; // return 1

But this outputs 2:

int bracketsTest = 0;
int resultBrackets = 1 + bracketsTest++ + bracketsTest; // return 2

I lived in the world where both snippets should be equal, since in both results we do the following:

  1. 1 + 0 + bracketsTest // bracketsTest = 0 and we put zero in bracketsTest++, after that bracketsTest = 1
  2. 1 + 0 + 1 = 2 // we put bracketsTest = 1 in last argument
    but turns out that increment/decrement operation is not highest prioritet operations? (since it is matter where we put bracketsTest in code snippet)

Upvotes: 3

Views: 476

Answers (2)

Zabuzard
Zabuzard

Reputation: 25903

Evaluation order

You seem to mix operator precendence with evaluation order. Please have a look at JLS§15.7. Evaluation Order:

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

Also:

The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

Additionally:

The Java programming language respects the order of evaluation indicated explicitly by parentheses and implicitly by operator precedence.

But that part only plays a role once you perform the operation itself. Before that happens, all operands will already be fully evaluated.


First snippet

Knowing that, we can decipher what is going on. The first snippet:

1 + bracketsTest + bracketsTest++

Will first of all evaluate all the operands (from left to right), so we get:

1. operand: 1
2. operand: 0
3. operand: 0 (and increment bracketsTest)

While evaluationg the third operand, it will increment bracketsTest. Now, it will add everything together and we get 1 + 0 + 0 = 1 as result.


Second snippet

The second snippet:

1 + bracketsTest++ + bracketsTest;

is evaluated from left to right as well, so we have:

1. operand: 1
2. operand: 0 (and increment bracketsTest)
3. operand: 1 (because it was just incremented)

Hence we receive 1 + 0 + 1 = 2.

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

The second addition expression is evaluated left to right, as:

int resultBrackets = 1 + bracketsTest++ + bracketsTest;

1               (add 1)
bracketsTest++  (add zero, then increment bracketsTest by 1)
bracketsTest    (add 1, the current value of bracketsTest)

The sum therefore evaluates to 2.

Upvotes: 1

Related Questions