wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Stack overflow exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Stack overflow exception" Watch "Stack overflow exception" New topic
Author

Stack overflow exception

Ankita Jain
Greenhorn

Joined: Sep 12, 2008
Posts: 13
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

Joined: Aug 03, 2008
Posts: 9291
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
jQuery in Action, 2nd edition
 
subject: Stack overflow exception
 
Similar Threads
Any Solution ?
ExamLab Thread question
Bug in question 13 Self Test 3 Book Kathy Sierra (SCJP6)
Dynamic Binding combined with super keyword
Any Solution of Deadlock?