有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么返回true而不是堆栈溢出?

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

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

    }

共 (2) 个答案

  1. # 1 楼答案

    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)**立即变为false,因为第一个操作数为false,所以不会计算下一个操作数,因此不会调用isSuch()方法

  2. # 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的级别时,&&操作符立即返回false,而不计算右侧,这是递归调用。这实际上使得n不大于2的情况成为基本情况。然后,前面的递归调用使用!操作符将其反转,返回true。两个调用都返回true,并且true被打印两次

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

    此外,如果您使用了非短路运算符&而不是&&,那么它将是一个无限递归循环,并且StackOverflowError将发生,而不管最初传递给isSuch的是什么数字