By Ziggy

2008-10-18 08:13:55 8 Comments

What is a StackOverflowError, what causes it, and how should I deal with them?


@Rahul Sah 2017-03-30 11:08:57

A StackOverflowError is a runtime error in java.

It is thrown when the amount of call stack memory allocated by JVM is exceeded.

A common case of a StackOverflowError being thrown, is when call stack exceeds due to excessive deep or infinite recursion.


public class Factorial {
    public static int factorial(int n){
        if(n == 1){
            return 1;
            return n * factorial(n-1);

    public static void main(String[] args){
        System.out.println("Main method started");
        int result = Factorial.factorial(-1);
        System.out.println("Factorial ==>"+result);
        System.out.println("Main method ended");

Stack trace:

Main method started
Exception in thread "main" java.lang.StackOverflowError
at com.program.stackoverflow.Factorial.factorial(
at com.program.stackoverflow.Factorial.factorial(
at com.program.stackoverflow.Factorial.factorial(

In the above case, it can be avoided by doing programmatic changes. But if the program logic is correct and it still occurs then you stack size needs to be increased.

@Sean 2008-10-18 08:34:31

Parameters and local variables are allocated on the stack (with reference types, the object lives on the heap and a variable in the stack references that object on the heap). The stack typically lives at the upper end of your address space and as it is used up it heads towards the bottom of the address space (i.e. towards zero).

Your process also has a heap, which lives at the bottom end of your process. As you allocate memory, this heap can grow towards the upper end of your address space. As you can see, there is a potential for the heap to "collide" with the stack (a bit like tectonic plates!!!).

The common cause for a stack overflow is a bad recursive call. Typically, this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself forever. Or when the termination condition is fine, it can be caused by requiring too many recursive calls before fulfilling it.

However, with GUI programming, it's possible to generate indirect recursion. For example, your app may be handling paint messages, and, whilst processing them, it may call a function that causes the system to send another paint message. Here you've not explicitly called yourself, but the OS/VM has done it for you.

To deal with them, you'll need to examine your code. If you've got functions that call themselves then check that you've got a terminating condition. If you have, then check that when calling the function you have at least modified one of the arguments, otherwise there'll be no visible change for the recursively called function and the terminating condition is useless. Also mind that your stack space can run out of memory before reaching a valid terminating condition, thus make sure your method can handle input values requiring more recursive calls.

If you've got no obvious recursive functions then check to see if you're calling any library functions that indirectly will cause your function to be called (like the implicit case above).

@Ziggy 2008-10-18 09:04:51

Original poster: hey this is great. So recursion is always responsible for stack overflows? Or can other things be responsible for them as well? Unfortunately I am using a library... but not one that I understand.

@Ziggy 2008-10-18 11:26:31

Ha ha ha, so here it is: while (points < 100) {addMouseListeners(); moveball(); checkforcollision(); pause(speed);} Wow do I feel lame for not realizing that I would end up with a stackfull of mouse listeners... Thanks guys!

@JB King 2008-11-04 23:30:28

No, stack overflows can also come from variables being too big to allocate on the stack if you look up the Wikipedia article on it at .

@Hot Licks 2014-01-25 14:09:41

It should be pointed out that it's almost impossible to "handle" a stack overflow error. In most environments, to handle the error one needs to run code on the stack, which is difficult if there is no more stack space.

@jcsahnwaldt says GoFundMonica 2015-01-23 02:22:48

Java keeps heap and stack in different memory areas. (Most JVMs do, anyway.) They don't collide, the stack simply has a limited size. (Can be set with -Xss at program start.) Otherwise, the explanation is fine.

@jcsahnwaldt says GoFundMonica 2015-01-23 02:25:54

@JB King: Doesn't really apply to Java, where only primitive types and references are kept on the stack. All the big stuff (arrays and objects) is on the heap.

@user207421 2016-02-11 23:23:50

@HotLicks Code doesn't run on the stack.

@Hot Licks 2016-02-12 03:50:00

@EJP - I could have phrased that a little better. In most environments, to handle the error one needs to run code which utilizes the stack for call/return and variable storage -- difficult if there is no more stack space.

@Keale 2018-06-07 09:13:41

@Sean, I have approved an edit proposal to your answer, and added a minor clarification myself. I'm not a native speaker, though I'm fairly confident in my English, and this clarification is how I understood that particular sentence. If I misunderstood then please feel free to rollback :) Cheers~

@Sergiu 2014-01-25 14:01:00

The term "stack overrun (overflow)" is often used but a misnomer; attacks do not overflow the stack but buffers on the stack.

-- from lecture slides of Prof. Dr. Dieter Gollmann

@Varun 2015-03-26 13:06:54

To describe this, first let us understand how local variables and objects are stored.

Local variable are stored in stack: enter image description here

If you looked at the image you should be able to understand how things are working.

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, to avoid StackOverflowError.

An example throwing 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 until we pass in 0 as a parameter. However, in our example, we passed in the parameter from 1 and its increasing followers, consequently 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 sun.nio.cs.StreamEncoder.writeBytes(
        at sun.nio.cs.StreamEncoder.implFlushBuffer(
        at sun.nio.cs.StreamEncoder.flushBuffer(
        at StackOverflowErrorExample.recursivePrint(
        at StackOverflowErrorExample.recursivePrint(
        at StackOverflowErrorExample.recursivePrint(
        at StackOverflowErrorExample.recursivePrint(

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.

How to deal with the StackOverflowError

  1. 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.

  2. 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: -Xss<size>[g|G|m|M|k|K]

@goerlibe 2017-06-08 09:17:37

There seems to be a bug in some java versions when using windows where the -Xss argument only takes effect on new threads

@Vikram 2012-07-17 21:23:44

StackOverflowError is to the stack as OutOfMemoryError is to the heap.

Unbounded recursive calls result in stack space being used up.

The following example produces StackOverflowError:

class  StackOverflowDemo
    public static void unboundedRecursiveCall() {

    public static void main(String[] args) 

StackOverflowError is avoidable if recursive calls are bounded to prevent the aggregate total of incomplete in-memory calls (in bytes) from exceeding the stack size (in bytes).

@user8389458 2018-04-02 12:36:13

This is a typical case of java.lang.StackOverflowError... The method is recursively calling itself with no exit in doubleValue(), floatValue(), etc.

    public class Rational extends Number implements Comparable<Rational> {
        private int num;
        private int denom;

        public Rational(int num, int denom) {
            this.num = num;
            this.denom = denom;

        public int compareTo(Rational r) {
            if ((num / denom) - (r.num / r.denom) > 0) {
                return +1;
            } else if ((num / denom) - (r.num / r.denom) < 0) {
                return -1;
            return 0;

        public Rational add(Rational r) {
            return new Rational(num + r.num, denom + r.denom);

        public Rational sub(Rational r) {
            return new Rational(num - r.num, denom - r.denom);

        public Rational mul(Rational r) {
            return new Rational(num * r.num, denom * r.denom);

        public Rational div(Rational r) {
            return new Rational(num * r.denom, denom * r.num);

        public int gcd(Rational r) {
            int i = 1;
            while (i != 0) {
                i = denom % r.denom;
                denom = r.denom;
                r.denom = i;
            return denom;

        public String toString() {
            String a = num + "/" + denom;
            return a;

        public double doubleValue() {
            return (double) doubleValue();

        public float floatValue() {
            return (float) floatValue();

        public int intValue() {
            return (int) intValue();

        public long longValue() {
            return (long) longValue();

    public class Main {

        public static void main(String[] args) {

            Rational a = new Rational(2, 4);
            Rational b = new Rational(2, 6);

            System.out.println(a + " + " + b + " = " + a.add(b));
            System.out.println(a + " - " + b + " = " + a.sub(b));
            System.out.println(a + " * " + b + " = " + a.mul(b));
            System.out.println(a + " / " + b + " = " + a.div(b));

            Rational[] arr = {new Rational(7, 1), new Rational(6, 1),
                    new Rational(5, 1), new Rational(4, 1),
                    new Rational(3, 1), new Rational(2, 1),
                    new Rational(1, 1), new Rational(1, 2),
                    new Rational(1, 3), new Rational(1, 4),
                    new Rational(1, 5), new Rational(1, 6),
                    new Rational(1, 7), new Rational(1, 8),
                    new Rational(1, 9), new Rational(0, 1)};


            for (int i = 0; i < arr.length - 1; ++i) {
                if (arr[i].compareTo(arr[i + 1]) > 0) {

            Number n = new Rational(3, 2);


        public static <T extends Comparable<? super T>> void selectSort(T[] array) {

            T temp;
            int mini;

            for (int i = 0; i < array.length - 1; ++i) {

                mini = i;

                for (int j = i + 1; j < array.length; ++j) {
                    if (array[j].compareTo(array[mini]) < 0) {
                        mini = j;

                if (i != mini) {
                    temp = array[i];
                    array[i] = array[mini];
                    array[mini] = temp;


    2/4 + 2/6 = 4/10
    Exception in thread "main" java.lang.StackOverflowError
    2/4 - 2/6 = 0/-2
        at com.xetrasu.Rational.doubleValue(
    2/4 * 2/6 = 4/24
        at com.xetrasu.Rational.doubleValue(
    2/4 / 2/6 = 12/8
        at com.xetrasu.Rational.doubleValue(
        at com.xetrasu.Rational.doubleValue(
        at com.xetrasu.Rational.doubleValue(
        at com.xetrasu.Rational.doubleValue(
        at com.xetrasu.Rational.doubleValue(

Here is the source code of StackOverflowError in OpenJDK 7

@John S. 2016-02-11 23:02:33

Here's an example

public static void main(String[] args) {

public static int add5(int a) {
    return add5(a) + 5;

A StackOverflowError basically is when you try to do something, that most likely calls itself, and goes on for infinity (or until it gives a StackOverflowError).

add5(a) will call itself, and then call itself again, and so on.

@Yiling 2013-01-16 19:49:52

Here is an example of a recursive algorithm for reversing a singly linked list. On a laptop with the following spec (4G memory, Intel Core i5 2.3GHz CPU, 64 bit Windows 7), this function will run into StackOverflow error for a linked list of size close to 10,000.

My point is that we should use recursion judiciously, always taking into account of the scale of the system. Often recursion can be converted to iterative program, which scales better. (One iterative version of the same algorithm is given at the bottom of the page, it reverses a singly linked list of size 1 million in 9 milliseconds.)

    private static LinkedListNode doReverseRecursively(LinkedListNode x, LinkedListNode first){

    LinkedListNode second =; = x;

    if(second != null){
        return doReverseRecursively(first, second);
        return first;

public static LinkedListNode reverseRecursively(LinkedListNode head){
    return doReverseRecursively(null, head);

Iterative Version of the Same Algorithm:

    public static LinkedListNode reverseIteratively(LinkedListNode head){
    return doReverseIteratively(null, head);

private static LinkedListNode doReverseIteratively(LinkedListNode x, LinkedListNode first) {

    while (first != null) {
        LinkedListNode second =; = x;
        x = first;

        if (second == null) {
        } else {
            first = second;
    return first;

public static LinkedListNode reverseIteratively(LinkedListNode head){
    return doReverseIteratively(null, head);

@kevin 2013-10-24 01:48:38

I think with JVM, it doesn't actually matter what the spec your laptop is.

@Cheery 2008-10-18 10:06:02

Stack overflow means exactly that: a stack overflows. Usually there's a one stack in the program that contains local-scope variables and addresses where to return when execution of a routine ends. That stack tends to be a fixed memory range somewhere in the memory, therefore it's limited how much it can contain values.

If the stack is empty you can't pop, if you do you'll get stack underflow error.

If the stack is full you can't push, if you do you'll get stack overflow error.

So stack overflow appears where you allocate too much into the stack. For instance, in the mentioned recursion.

Some implementations optimize out some forms of recursions. Tail recursion in particular. Tail recursive routines are form of routines where the recursive call appears as a final thing what the routine does. Such routine call gets simply reduced into a jump.

Some implementations go so far as implement their own stacks for recursion, therefore they allow the recursion to continue until the system runs out of memory.

Easiest thing you could try would be to increase your stack size if you can. If you can't do that though, the second best thing would be to look whether there's something that clearly causes the stack overflow. Try it by printing something before and after the call into routine. This helps you to find out the failing routine.

@Pacerier 2012-01-29 14:09:06

Is there such a thing as a stack underflow ?

@Score_Under 2013-02-09 00:14:04

A stack underflow is possible in assembly (popping more than you pushed), though in compiled languages it'd be near impossible. I'm not sure, you might be able to find an implementation of C's alloca() which "supports" negative sizes.

@Koray Tugay 2015-05-02 21:58:42

Stack overflow means exactly that: a stack overflows. Usually there's a one stack in the program that contains local-scope variables -> No, every thread has its own stack which contains stack frames for every method invocation that contains local variables..

@splattne 2008-10-18 08:43:31

The most common cause of stack overflows is excessively deep or infinite recursion. If this is your problem, this tutorial about Java Recursion could help understand the problem.

@Khoth 2008-10-18 08:31:36

If you have a function like:

int foo()
    // more stuff

Then foo() will keep calling itself, getting deeper and deeper, and when the space used to keep track of what functions you're in is filled up, you get the stack overflow error.

@Cheery 2008-10-18 09:29:26

Wrong. Your function is tail-recursive. Most compiled languages have tail-recursion optimizations. This means the recursion reduces into a simple loop and you will never hit stack overflow with this piece of code on some systems.

@horseyguy 2009-08-10 19:52:32

Cheery, which non-functional languages support tail recursion?

@Pacerier 2012-01-29 14:07:07

@banister and some implementations of javascript

@Ajit K'sagar 2017-11-19 18:50:29

@horseyguy Scala has support for Tail recursion.

@Pixel 2018-01-18 22:35:30

This captures the essence of what can create a stack overflow. Nice.

@Greg 2008-10-18 08:19:15

A stack overflow is usually called by nesting function calls too deeply (especially easy when using recursion, i.e. a function that calls itself) or allocating a large amount of memory on the stack where using the heap would be more appropriate.

@Greg 2008-10-18 08:23:34

Oops, didn't see the Java tag

@Ziggy 2008-10-18 08:26:57

Also, from the original poster here: nesting functions too deeply in what? Other functions? And: how does one allocate memory to the stack or heap (since, you know, I've clearly done one of these things without knowing).

@Chris Jester-Young 2008-10-18 09:25:40

@Ziggy: Yes, if one function calls another function, which calls yet another function, and so on, after many levels, your program will have a stack overflow. [continues]

@Chris Jester-Young 2008-10-18 09:26:55

[...continued] In Java, you can't directly allocate memory from the stack (whereas in C, you can, and this would then be something to watch for), so that's unlikely to be the cause. In Java, all direct allocations come from the heap, by using "new".

@Pacerier 2012-01-29 14:08:29

@ChrisJester-Young Isn't it true that if I have 100 local variables in a method, all of it goes on the stack without exceptions?

@Chris Jester-Young 2012-01-30 05:53:44

@Pacerier: The local variables are all on the stack, correct. However, if the variables are of reference type, the objects they point to are all allocated on the heap (except cases where escape analysis optimisation kicks in). (NB: In Java, arrays are of a reference type, even arrays of primitives.)

@Pacerier 2012-01-30 06:13:54

@ChrisJester-Young Btw I was wondering is there any chance that a variable on the stack could be seen by other threads?

@Chris Jester-Young 2012-01-30 06:40:49

@Pacerier: The variable itself? No (stacks are thread-local). The objects pointed to by reference variables? Yes.

@Pacerier 2012-01-30 08:00:31

@ChrisJester-Young sry I think I've phrased it wrongly. I actually meant "is there any chance a stack could be a non-thread-local stack" ?

@Chris Jester-Young 2012-01-30 16:10:32

@Pacerier: A non-thread-local stack doesn't make any sense: two threads would then scribble on each other's call frames!

@Pacerier 2012-01-31 07:50:04

@ChrisJester-Young Do you mean that primitive variables that are shared across threads are allocated on the heap?

@Chris Jester-Young 2008-10-18 08:17:19

Like you say, you need to show some code. :-)

A stack overflow error usually happens when your function calls nest too deeply. See the Stack Overflow Code Golf thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).

@Ziggy 2008-10-18 08:27:31

I would totally like to add code, but as I don't know what causes stack overflows I am not sure what code to add. adding all the code would be lame, no?

@Chris Jester-Young 2008-10-18 09:37:22

Is your project open-source? If so, just make a Sourceforge or github account, and upload all your code there. :-)

@Ziggy 2008-10-18 09:49:21

this sounds like a great idea, but I am such a noob that I don't even know what I would have to upload. Like, the library that I am importing classes that I am extending etc... are all unknowns to me. Oh man: bad times.

Related Questions

Sponsored Content

19 Answered Questions

55 Answered Questions

[SOLVED] How to create a memory leak in Java?

13 Answered Questions

[SOLVED] How to print the full traceback without halting the program?

43 Answered Questions

5 Answered Questions

[SOLVED] Why is it possible to recover from a StackOverflowError?

  • 2014-03-02 13:54:56
  • user3370796
  • 5345 View
  • 99 Score
  • 5 Answer
  • Tags:   java stack-overflow

32 Answered Questions

6 Answered Questions

[SOLVED] Try-finally block prevents StackOverflowError

1 Answered Questions

[SOLVED] Should the JVM be restated on StackOverflowError?

19 Answered Questions

Sponsored Content