-1

In the recursion, if I have the following sample code

public class StringPractice {
    public static void main(String[] args){     
        hello();
    }
    public static void hello(){

        System.out.println("heloo world!");
        hello();
    }
}

it will result in StackOverFlowError. However if I'm using while loop, for example while(true) and printout the function hello, it keeps looping with the output but doesn't give us StackOverFlowError. Can somebody explain why? Whats the different ?

1 Answers1

0

You have no logic testing whether or not to stop the recursion, so the function is called again and again, adding onto the call stack until you run out of memory.

public class StringPractice {
    public static void main(String[] args){     
        hello(10);
    }
    public static void hello(int n){

        System.out.println("hello world! " + n);
        hello(n - 1); // TODO do a test before calling this function again.
    }
}
Kimball Robinson
  • 3,287
  • 9
  • 47
  • 59
  • and why if Im using while loop without logic testing it won't result in stackoverflow? the loop just keeps looping. – fadhil suhendi Jan 13 '16 at 23:38
  • oh thanks, I think I get it now! – fadhil suhendi Jan 13 '16 at 23:40
  • You can make a loop continue forever too, unless you provide a condition that will terminate it. `while(true) { /* do stuff infinitely */ }. The reason this doesn't run out of memory is that each function call is treated like a new set of variables -- meaning more memory is required at each recursion (you need to read up on how the function call stack works). A loop doesn't necessarily require more memory each time. – Kimball Robinson Jan 14 '16 at 18:02