Solution for java.lang.StackOverflowError exception in java

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

java stack overflow error 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 but thrown by java virtual machines.

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 the 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 at the bottom of the call stack. please note that each thread has its 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 the hello() method recursively calls the same method infinite times, this makes call stack store all method entries in memory. and size of the call stack is grown and the exception is thrown when the call stack is unable to accommodate enough size for all these entries in memory. here stack is full with all the entries, StackOverflowError is thrown. 3. hello, the method is called recursively itself infinite times. so please make sure that avoid recursive infinite method calls.

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

Please leave a comment on your thoughts on this.