Home » Java Basics » exceptions » java.lang.StackOverflowError – How to solve StackOverflowError

About Sotirios-Efstathios Maneas

Sotirios-Efstathios Maneas
Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.

java.lang.StackOverflowError – How to solve StackOverflowError

In this tutorial we will discuss about the StackOverflowError in Java. This error is thrown to indicate that the application’s stack was exhausted, due to deep recursion.

The StackOverflowError extends the VirtualMachineError class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the VirtualMachineError extends the Error class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.

Finally, the StackOverflowError exists since the 1.0 version of Java.

The Structure of StackOverflowError


  • StackOverflowError()
  • Creates an instance of the StackOverflowError class, setting null as its message.

  • StackOverflowError(String s)
  • Creates an instance of the StackOverflowError class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The StackOverflowError in Java

When a function call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).

The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided.

An example that throws a StackOverflowError is shown below:


public class StackOverflowErrorExample {
	public static void recursivePrint(int num) {
		System.out.println("Number: " + num);
		if(num == 0)
	public static void main(String[] args) {

In this example, we define a recursive method, called recursivePrint that prints an integer and then, calls itself, with the next successive integer as an argument. The recursion ends once we invoke the method, passing 0 as a parameter. However, in our example, we start printing numbers from 1 and thus, the recursion will never terminate.

A sample execution, using the -Xss1M flag that specifies the size of the thread stack to equal to 1MB, is shown below:

Number: 1
Number: 2
Number: 3
Number: 6262
Number: 6263
Number: 6264
Number: 6265
Number: 6266
Exception in thread "main" java.lang.StackOverflowError
        at java.io.PrintStream.write(PrintStream.java:480)
        at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
        at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
        at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
        at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
        at java.io.PrintStream.write(PrintStream.java:527)
        at java.io.PrintStream.print(PrintStream.java:669)
        at java.io.PrintStream.println(PrintStream.java:806)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:4)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
        at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)

Depending on the JVM’s initial configuration, the results may differ, but eventually the StackOverflowError shall be thrown. This example is a very good example of how recursion can cause problems, if not implemented with caution.

More about the StackOverflowError in Java

The following example demonstrates the risk of having cyclic relationships between classes:


class A {
	private int aValue;
	private B bInstance = null;
	public A() {
		aValue = 0;
		bInstance = new B();
	public String toString() {
		return "";

class B {
	private int bValue;
	private A aInstance = null;
	public B() {
		bValue = 10;
		aInstance = new A();
	public String toString() {
		return "";

public class StackOverflowErrorToStringExample {
	public static void main(String[] args) {
		A obj = new A();

In this example, we defined two classes, A and B. The class A contains one instance of the B class, while, the B class contains one instance of the A class. Thus, we have a circular dependency between these two classes. Furthermore, each toString method, invokes the corresponding toString method of the other class, and so on, which results in a StackOverflowError.

A sample execution is shown below:

Exception in thread "main" java.lang.StackOverflowError
	at main.java.B.(StackOverflowErrorToStringExample.java:24)
	at main.java.A.(StackOverflowErrorToStringExample.java:9)
	at main.java.B.(StackOverflowErrorToStringExample.java:24)
	at main.java.A.(StackOverflowErrorToStringExample.java:9)
	at main.java.B.(StackOverflowErrorToStringExample.java:24)
	at main.java.A.(StackOverflowErrorToStringExample.java:9)

How to deal with the StackOverflowError

  • The simplest solution is to carefully inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code being recursively called. Once you detect these lines, you must carefully inspect your code and understand why the recursion never terminates.
  • If you have verified that the recursion is implemented correctly, you can increase the stack’s size, in order to allow a larger number of invocations. Depending on the Java Virtual Machine (JVM) installed, the default thread stack size may equal to either 512KB, or 1MB. You can increase the thread stack size using the -Xss flag. This flag can be specified either via the project’s configuration, or via the command line. The format of the -Xss argument is:

Download the Eclipse Project

This was a tutorial about the StackOverflowError in Java.

You can download the full source code of this example here: StackOverflowErrorExample.zip.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....



Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.