Java Reference
In-Depth Information
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