0

Suppose that i have the following code:

    int j = 0;
    boolean x = true, y = false, z;
    z = (x || ((j++) == 0));
    z = (y || ((j += 2) > 0));

the final value of j will be 2

z in the 1st assign, will have true or false, which is true

z in the 2nd assign, will have false or true, which is true

why the final value is 2? what is the difference between having true || false and false||true ?

I am not asking about "short-circuit" operators,

I just need more explanation for the assign operator, and how the first j didn't changed the value of j and the 2nd did.

ajc
  • 1,685
  • 14
  • 34
zyz82
  • 173
  • 1
  • 12

1 Answers1

3

the || operator validates from left to right.

In your case, the first condition true || false, once || finds true, it does not have to check for the other condition as the result is going to be true regardless. Thats the reason here x||((j++)==0) once x = true if figured, the next statement (j++==0) is skipped.

the second condition false || true, once || finds false, it have to check for next condition.

Ref > https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

ajc
  • 1,685
  • 14
  • 34