java.lang.StackOverflowError exception

This post shows how to create a StackOverflowError with a recursion. Let’s look at the error message first:
Exception in thread “main” java.lang.StackOverflowError
at ch.allenstudy.newway01.Recursion1.f(Recursion1.java:9)
at ch.allenstudy.newway01.Recursion1.g(Recursion1.java:14)
at ch.allenstudy.newway01.Recursion1.f(Recursion1.java:9)
at ch.allenstudy.newway01.Recursion1.g(Recursion1.java:14)

Here’s the code:
package ch.allenstudy.newway01;

public class Recursion1 {
public int i;

void f() {
g();
}

void g() {
f();
}

}

class RecursionTester {
public static void main(String[] args) {
Recursion1 n = new Recursion1();
n.g();
}
}

You can see that f() method calls g() method, then g() calls f(); it’s a recursion.

Why it gets the StackOverFlow?
That’s because in the program, the application executes the code one by one.
{

myFunct(int a); //Address in memory stack is A
next line //Address in memory stack is B

}

The program make the call to myFunct(int a), this method will be executed. While, after finish execution, the system need send a signal to myFunct(int a), tell it where you should come back and continue. The signal here is called “returned address”; but notice, it’s the return address of “next line”, so that it can continue to run.
And this “returned address” is pushing into Stack.
In up sample, you see, the f() and g() call each other in an infinite loop, every time they call each other, there will add a “returned address” into stack.
After a while, the stack is full. Then have the overflow.

转载于:https://www.cnblogs.com/backpacker/archive/2011/12/01/2271194.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值