|
Java supports recursive methods, i.e. even if you're already inside methodA() you can call methodA(). The easiest way I can think of to explain recursion is to look at a simple acronym, GNU. The GNU project, among other things, is trying to produce free versions of the Unix operating system and many Unix tools, such as lex, yacc, and cc. One minor problem with this effort is that the name Unix is trademarked so the GNU project can't use it. Hence, instead of Unix, we have GNU, where GNU stands for "Gnu's Not Unix.The definition of GNU refers to itself; that is, it's recursive. So what is GNU? One level deeper it's (Gnu's Not Unix)'s Not Unix.One level deeper still, it becomes ((Gnu's Not Unix)'s Not Unix)'s Not Unix.And so on, ad infinitum. It's like standing between a pair of mirrors. The images just fade off into the distance with no clear end in sight. In computer programming recursion is achieved by allowing a method to call itself.
You probably already see one problem with recursion. Where does it all end? In fact when you write recursive methods you have to be careful to include stopping conditions. Although Java doesn't put any particular limits on the depth to which you can expand a recursion, it is very possible to have a run-away recursion eat up all the memory in your computer.
Let's look at an example. n! (pronounced "En-factorial) is defined as n times n-1 times n-2 times n-3 ... times 2 times 1 where n is a positive integer. 0! is defined as 1. As you see n! = n time (n-1)!. This lends itself to recursive calculation, as in the following method:
public static long factorial (int n) { if (n == 0) { return 1; } else { return n*factorial(n-1); } } Something to think about: What happens if a negative integer is passed into the factorial method? For example suppose you ask for factorial(-1). Then you get the following chain of calls: -1 * -2 * -3 * -4 * .... If you're lucky your program may unexpectedly pop into the positive numbers and count down to zero. If you're not, your program will crash with a StackOutOfMemoryError. Stopping conditions are very important. In this case you should check to see if you've been passed a negative integer; and, if you have been, return infinity. ( The factorial is a special case of the gamma function for non-negative integers. Although the factorial function is only defined for non-negative integers, the gamma function is defined for all real numbers. It is possible to show that the gamma function is infinite for negative integers. ) Java doesn't support infinite values for longs, though, so return the warning value -1 instead. (Java does support infinite values for floats and doubles.) Here's a better recursive factorial method:
public static long factorial (int n) { if (n < 0) { return -1; } else if (n == 0) { return 1; } else { return n*factorial(n-1); } }
|