aspose file tools
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

Stack overflow exception

Ankita Jain

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();
void go1()
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

Joined: Aug 03, 2008
Posts: 9327

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
It is sorta covered in the JavaRanch Style Guide.
subject: Stack overflow exception