File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why am i getting StackOverflowError? 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 "Why am i getting StackOverflowError?" Watch "Why am i getting StackOverflowError?" New topic

Why am i getting StackOverflowError?

Vinay Belagavi

Joined: Jun 15, 2006
Posts: 29

When I compile and run the program, I get a StackOverflowError.I am not able to understand the reason.

Is it because I have created an instance of the class in the constructor?The program works fine if line 6 and 7 are removed.

The documentation says that
stack overflow occurs because an application recurses too deeply
what do you mean by application recurses too deeply?

Can anybody explain this to me.

I am breaking my head over this
Simeon Cherniy

Joined: Jul 26, 2006
Posts: 21
You call:
InstanceTest it = new InstanceTest(); -> constructor called
InstanceTest it1 = new InstanceTest(); -> constructor called
Too deeply means that ideally this recursion is infinite

5-year Student of <br />Moscow Institute of Physics and Technology.
Watsh Rajneesh
Ranch Hand

Joined: Apr 17, 2006
Posts: 110
Stack overflow happens as you are calling the constructor (new InstanceTest()) within the constructor body - and this makes it a recursive function.

The function calls are stored on the stack of the process (jvm's process' stack memory). When a function is called, its return address and local vars/references are kept on the top of the stack. If this function calls another function (or itself - as in recursion) then the stack size grows to accomodate the new function's info. When there is no exit criteria specified for a recursion (as in your case) the functions keep adding to the top of the stack and there comes a time when stack size reaches the maximum possible size and the JVM process balks out complaining an overflow.

SCJP 5.0 (90%), SCDJWS 1.4 (88%), SCWCD 1.4 (82%), SCBCD 1.3 (85%)
Vinay Belagavi

Joined: Jun 15, 2006
Posts: 29
Thanks Simeon and Rajneesh,

Itz all clear now
It is sorta covered in the JavaRanch Style Guide.
subject: Why am i getting StackOverflowError?
Similar Threads
How to create object to a specific class by using its name as string variable with out using new.
SCJP Generics geting the compilation Error
Question on casting
Two simpe methods calling each other not working as expected