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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With