为什么这个 return true true 而不是堆栈溢出?

Why does this return true true and not stack overflow?

为什么这不是无限递归循环?

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);

    }

这不是无限递归循环,因为它最终会停止。它停止是因为 && 运算符是 短路运算符 JLS, Section 15.23,描述了&&运算符:

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.

当递归达到n不大于2的层次时,那么&&运算符立即returnsfalsewithout 评估右侧,这是递归调用。这有效地使 n 不大于 2 的情况成为基本情况。然后之前的递归调用使用 ! 运算符将其反转,returning true。两次调用 return true,并且 true 被打印两次。

值得注意的是,虽然这是一个相当深的递归,但堆栈大小足以处理这个问题。但是对于 WhosebugError 的发生来说,不必是一个无限递归循环。它所需要的只是递归得足够远。调用 isSuch(99999) 足以在我的盒子上引起 WhosebugError

此外,如果您使用非短路运算符 & 而不是 &&,那么它将是一个无限递归循环,并且无论如何都会出现 WhosebugError最初传递给 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.

在您的示例代码中,当 n 的值等于 2 时,条件 **n > 2 && !isSuch(n - 2)** 由于第一个操作数为假,因此立即变为假,因此不会评估下一个操作数,因此不会调用 isSuch() 方法。