Search code examples
javastack-overflow

stack overflow explanation from code sample


I saw this code snippet from my exam, and my first hint would be it will throw StackOverFlowError

for (int i = 10; i > 5; i++) {
    if(i == 1000) i = 10;
    System.out.println(i);
}

It happens to be that its not. From the code sample, can you please explain why this is not going to throw StackOverFlowError.


Solution

  • To have a StackOverflowError, you have to be adding things to the call stack.

    You're adding calls to System.out.println, but they simply don't stack on top of one another, so there would only be one call on the stack at any given time.

    Now, an example of StackOverflowError would be recursion that does not sufficiently resolve the previous entries on the call stack; something that simply has too many method calls to itself for a sufficiently large parameter, or creates more calls to itself for every call to itself than it can deal with. (The Ackermann function is a notorious example of this.)

    If we define factorial as thus:

    public long factorial(long value) {
        return value == 0 ? 1 : value * factorial(value - 1);
    }
    

    ...and give it a sufficiently large value...

    System.out.println(factorial(1891279172981L));
    

    ...then we won't have enough stack space to handle all 1891279172981 of those entries on to it.