Confused about java operator precedence calcul results

Viewed 123

I have an expression that I'm confused with the results how it's calculated

int a = 7;
boolean res = a++ == 7 || a++ == 9;
System.out.println("a = " + a);
System.out.println("res = " + res);

This give me as results :

a = 8
res = true

I didn't understand why a get the value 8 I expect a = 9 as a results can some one explain me how it's calculated ?

4 Answers

Lazy evaluation is used here. In alternative only one operand (argument) need to be true to make alternative result true. Left argument is true in this case (because you use postincrementation, a will be incremented after check), so there is no need to check left side of alternative.

It means second incrementation won't be executed.

The interesting part is this:

boolean res = a++ == 7 || a++ == 9;

The evaluation starts here:

a++ == 7

and it actually is translated to: a == 7 and then a = a + 1
so a == 7 evaluates to true and then a becomes equal to 8.
Since the 1st part of the boolean expression is true,
because of Short Circuit Evaluation for || (the OR logical operator),
the 2nd part a++ == 9 is not evaluated/executed.
This means that a is not incremented again.
If you want to test your understanding of this concept, make this change:

boolean res = ++a == 7 || a++ == 9;

and predict the result before you run the code.

the ++ operator actually changes the variable value after the statement is executed, when written after the variable (a++ instead of ++a). So res becomes true because a == 7, and after this a's value is changed to 8

Lets analyse what happen step by step :

int a = 7;
boolean res = 
               a++ == 7               // a in this step is equal to 7 not 8
                         || a++ == 9; // even in this step, when the statement is end
                                      // a it will incremented to 8

so the first statement a++ == 7 is true, for that you get res => true and a => 8

for more details read this Difference between i++ and ++i in a loop?

Related