Win a copy of Learn Spring Security (video course) this week in the Spring 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: 9509
22
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic