0

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.

5
  • 3
    Well, for one thing, there are no method calls stacking. Commented Jan 30, 2015 at 2:08
  • but the local variable inside the for block, isnt it also in the stack? Commented Jan 30, 2015 at 2:10
  • 2
    @Ryan yes, and it's created when it enters scope (before the first iteration) and destroyed when it leaves scope (after the last iteration). And there is only one of it. Commented Jan 30, 2015 at 2:11
  • i see, because its just initialized once, how about the println() this is a method on stack. right Commented Jan 30, 2015 at 2:13
  • 2
    You should explain why you think it will throw a StackOverflowError. Commented Jan 30, 2015 at 2:13

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Note that you are adding each call to System.out.println sequentially after the previous call has been popped off the stack. At most there would only be one call on the stack in the example.
Note that it's an infinite loop. It does not loop only 5 times.
Silly me. I've been seeing angle brackets all day, and now's a good time to get 'em mixed up...thanks for that @immibis.
hope i can give two correct answer. Thanks, also for the example.
3

This snippet causes an infinite loop, but not an infinite recursion (since you don't have a method calling itself infinite times). Therefore it will not cause a StackOverflowError.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.