This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
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: 9466

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
I agree. Here's the link:
subject: Stack overflow exception
It's not a secret anymore!