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);
}
# 1 楼答案
在示例代码中,当n的值等于2时,条件
**n > 2 && !isSuch(n - 2)**
立即变为false,因为第一个操作数为false,所以不会计算下一个操作数,因此不会调用isSuch()方法# 2 楼答案
它不是一个无限递归循环,因为它最终会停止。它停止是因为
&&
操作符是一个短路操作符。JLS, Section 15.23描述了&&
操作符:当递归达到
n
不大于2
的级别时,&&
操作符立即返回false
,而不计算右侧,这是递归调用。这实际上使得n
不大于2
的情况成为基本情况。然后,前面的递归调用使用!
操作符将其反转,返回true
。两个调用都返回true
,并且true
被打印两次值得注意的是,虽然这是一个相当深的递归,但堆栈大小足以处理这个问题。但是
StackOverflowError
发生时不需要无限递归循环。它所需要的只是递归足够远。调用isSuch(99999)
就足以在我的框上引起StackOverflowError
此外,如果您使用了非短路运算符
&
而不是&&
,那么它将是一个无限递归循环,并且StackOverflowError
将发生,而不管最初传递给isSuch
的是什么数字