简体   繁体   中英

Why does this return true true and not stack overflow?

Why isn't this an infinite recursive loop?

public static void main(String[] args) {
        System.out.println(isSuch(99) + " " + isSuch(100));
    }

    public static boolean isSuch(int n)
   {
      System.out.println("n is currently at "+ n);
       return n > 2 && !isSuch(n - 2);

    }

It is not an infinite recursive loop, because it will eventually stop. It stops because the && operator is a short-circuiting operator . The JLS, Section 15.23 , describes the && operator:

The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.

When the recursion reaches a level where n is not greater than 2 , then the && operator immediately returns false without evaluating the right hand side, which is the recursive call. That effectively makes the case where n is not greater than 2 the base case. Then previous recursive calls invert it with the ! operator, returning true . Both calls return true , and true is printed twice.

It is worth noting that while this is a pretty deep recursion, the stack size was more than enough to handle this. But it's not necessary to be an infinitely recursing loop for a StackOverflowError to occur. All it needs is to recurse far enough. Calling isSuch(99999) is enough to cause a StackOverflowError on my box.

Also, if you had used the non-short-circuiting operator & instead of && , then it would be an infinitely recursive loop, and a StackOverflowError would occur regardless of what number was originally passed to isSuch .

Short-Circuit Logical Operators

The OR operator results in true when first operand is true, no matter what the second operand is. The AND operator results in false when first operand is false, no matter what the second operand is. If you use the || and &&, Java will not evaluate the right-hand operand when the outcome can be determined by the left operand alone.

In your sample code when value of n becomes equal to 2, condition **n > 2 && !isSuch(n - 2)** immediately becomes false since first operand is false, so next operand will not be evaluated thus isSuch() method will not be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM