Wednesday, April 24, 2019

StackOverflowError in java

Q- What is a Stack Overflow Error in java? or  What is StackOverflowError in Java?
Why and when StackOverflowError occur in java?

StackOverflowError is run time exception extends java.lang.Error in java.
StackOverflowError is occur due to insufficient or low memory in stack during method execution.
because in java, Stack is used to execute methods of a class.

When a method of class is invoked by a Java application, a stack frame is allocated to execute a method in stack.
If method execution required the more space then the space allocated to stack by JVM.
This may occur due to not proper programming into method like non controllable recursion call etc.
If there is no space for a "new stack frame" then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).

The most of case, it can possibly exhaust a Java application's stack is recursion.

StackOverflowError Examplpe in java

public class StackOverflowExample {
 // recursivePrint to print recursively
 public static void recursivePrint(int num) {
  System.out.println("Number: " + num);
  if (num == 0)

 public static void main(String[] args) {
  try {
  } catch (Exception e) {

Exception in thread "main" java.lang.StackOverflowError
        at sun.nio.cs.StreamEncoder.writeBytes(
        at sun.nio.cs.StreamEncoder.implFlushBuffer(
        at sun.nio.cs.StreamEncoder.flushBuffer(
        at StackOverflowExample.recursivePrint(

Q- How to avoid StackOverflowError  in java? or How to avoid java.lang.StackOverflowError?

1. Code should be written properly.
2. Increase memory :
To increase the memory of JVM allocation and thread stack size for Tomcat from the command line Open the catalina.bat file (TomcatInstallDirectory/bin /catalina.bat). Add the following below line:

set JAVA_OPTS=%JAVA_OPTS% -Xms1024m  -Xmx1024m

  • Xms is the initial (start) memory pool.
  • Xmx is the maximum memory pool.
  • Xss is the thread stack size.

No comments:

Post a Comment