Search code examples
javaif-statementdecrement

Question regarding post decrement in loop jointed with if


What is the difference between the following to code? The result is different. b is some String and int j = b.length() - 1

The if branch is in a loop and runs many times if this makes any difference.

if (j >=0 && b.charAt(j) == '1') {
    j--;
    carry ++;
}

vs.

if (j >=0 && b.charAt(j--) == '1') {
    carry ++;
}

Solution

  • What happens if the 1st condition is true and the 2nd condition is false?

    //   true              false
    //    V                  V
    if (j >=0 && b.charAt(j) == '1') foo();   // foo not executed, j not changed
    
    //    V                  V
    if (j >=0 && b.charAt(j--) == '1') foo(); // foo not executed, j decremented