Solution for java.lang.StackOverflowError exception in java

StackOverflowError is one of frequent exception/issue in java projects. This exceptions should not be caught by the programmer but thrown by Java virtual machine at runtime. whenever this exception is thrown, application stopped its execution

java stackoverflowerror class overview:-

StackOverflowError extends java.lang.VirtualMachineError class which in turns extends java.lang.Error. so what is java.lang?Error?. Error class extends Throwable class specifies unusual errors that application unable to catch these exceptions. These exceptions are not programming related exceptions but thrown by java virtual machine.

StackOverflowError exception thrown in the method when the method is called recursively in infinite times.

Let us see the below program how it throws the exceptions

public class StackDemo {  
 public static void main(String[] args) {  
  StackDemo sd=new StackDemo();  
 public void hello(){  

output for the above program is an exception with a message like “Exception in thread “main” java.lang.StackOverflowError” thrown by applications.

The below is the program execution in memory in java virtual machine
1. The main method is the starting point for the execution in the parent thread called main, once execution starts, the main method makes one entry in the bottom of the call stack. please note that each thread has one own call stack.
2. After that,StackDemo Object is created and method hello() is called from the main thread, method area would be stored in the call stack above the main () method area.
this method calls hello() method recursively calls the same method infinite times, this makes call stack stores all method entries in memory. and size of the call stack is grown and the exception is thrown when call stack unable to accommodate enough size for all these entries in memory. here stack is full with all the entries, StackOverflowError is thrown.
3. hello method is called recursively itself infinite times. so please make sure that avoid recursive infinite method calls.

These errors are thrown by Java virtual machine, so be careful with recursive calls in the methods.

Please leave a comment your thoughts on this.


its very helpful about jave. Thanks admin for this…

mahbub - Mar 5, 2012

its very helpful about jave. Thanks admin for this information shear with us.

thanks for information……

Similar Posts