Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 14 ■ RECURSION

public static void main(String[] args) {
Factorial factorial = new Factorial();
System.out.println(factorial.calculate(4));
}


}


In the calculate method, after checking for valid input, check for the stop condition, which is the
argument “1”. (Note the recursion in the preceding sentence: “In... after... .” It really is common.)


When to Avoid Recursion


The biggest problem with recursion is that each pass through the method puts another object in the call
stack. If you have a lot of recursion to do, you can overflow the stack. As the following image shows, there
are four instances of the calculate method on the stack when the factorial of four (4!) is calculated.


Figure 14-1. calculate Methods on the Call Stack

Free download pdf