Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Stack overflow exception

 
Ankita Jain
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class test
{
test t= new test(); //-----(1)
public static void main(String[] args)
{
new test().go();
System.out.println("main method");
}

void go()
{
test t= new test();
go1();
}
void go1()
{
t.go2();
}
void go2()
{
System.out.println("go2 method");
}

}
Can anyone please tell me why this code is giving stack overflow exception?
and not with static keyword at (1)?
 
Ankit Garg
Sheriff
Posts: 9593
34
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well this is because every time you create an instance of test class, one more instance is created in it (t declared at (1)). When that instance is created, one more instance is created in it and so on.

But when you make that instance static, then it get's initialized only once and not every time when you create an instance.

The StackOverflowError occurs because there are too many pending constructor calls. If you modify your class and add a big object to it as int[] i = new int[10000], then you will get an OutOfMemoryError...
 
Ever since I found this suit I've felt strange new needs. And a tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!