1

I am working with a textbook right now and one of the answers to the 'test' questions seems wrong to me. They have the following code example:

while(true){
        doStuff();
    }

    static void doStuff(){
        for (int i = 10; i > 5; i++){
            if(i > 100000){
                break;
            }
        }
    }

And according to them, the answer is

"F: The program will hang without ever completing"

As opposed to

"C: A StackOverflowError might be thrown"

I suppose I don't understand why a StackOverflow error would NOT eventually be thrown in this infinite loop? Is it because I have not marked it as an exception via try/ catch / throws? Would it be different if we were creating variables within that for loop which take up memory? Or am I misunderstanding entirely?

PGMacDesign
  • 6,092
  • 8
  • 41
  • 78
  • Why do you think it should throw `StackOverflowError`? – Rohit Jain Mar 19 '15 at 18:36
  • 1
    In this case, a stack overflow would not occur. However, if instead of the loop you used recursion and ended up in an infinite recursive call, you WOULD have a stack overflow. This is because each function call goes onto the stack until it is removed or overflows. – Evan Bechtol Mar 19 '15 at 18:38
  • 1
    It will just hang without ever completing. When doStuff() returns, the stack it used will be cleaned before next call. If it were to cause infinite recursion (method calling itself over and over again), then you'd get a StackOverflowException. – esaj Mar 19 '15 at 18:38
  • 1
    Very simplified: The stack is used whenever you call a method. When you return from this method, the stack memory is again free. If you don't return, but, for example, call the same method recursively, the memory will not be freed and thus StackOverflow. Creating objects or doing non-recursive loops will not fill your stack. – Florian Schaetz Mar 19 '15 at 18:38
  • Excellent answers, thank you Florian, esaj, and Evan, that helps me understand what I got wrong. Appreciate your time. – PGMacDesign Mar 19 '15 at 19:04

0 Answers0