Search code examples
javabooleanboolean-logicboolean-expressionboolean-operations

Boolean operators and parentheses


Can someone explain to me why this is returning false? All of these statements should be true, except for the one with OR statements - so it should be fine, yet it returns false when I run it.

c1 = 2;
c2 = 2; 
row = 3;
column = 2;

if ((c2 < 3) && (row == c1++) && ((column == c2) || (column == c2++))){
    return true;

Solution

  • row == c1++ is false since post increment operator returns the previous value of the incremented variable. This means your are checking if 3 == 2, which is false.

    If you switch to pre-increment, you'll get true:

    if ((c2 < 3) && (row == ++c1) && ((column == c2) || (column == c2++))) {
        return true;
    }
    

    BTW, you can simply write

    return (c2 < 3) && (row == ++c1) && ((column == c2) || (column == c2++));
    

    instead of the if statement.