Recursion Brief Intro.

Recursion is a way to iterate (to loop) without using the traditional for and while control structures. With recursion, multiple iterations blocks of code are accomplished by calling other instances of a the same method from within the method itself. You'll quite often hear recursion referred to as a method calling itself. But this is not actually true since what happens is new instances of the method are loaded into memory as the recursive "loop" progresses.

As with all loops, it is important to have a way for the loop to end. But since it is multiple instances of the method, it cannot be one variable which stops all instances of the method, rather, the "Loop Control Variable" of each instance will have to look after ending its own instance. But the problem is that each instance of the method will have to wait for the call to the other instance to end, and that instance in turn needs to wait for the instance that it called to end, and so on. So sooner or later one of the instances that is called will have to end before making another call. Then all of the other instances of the method on up the line can end one at a time. To appreciate this rather complex series of events, consider the following example of a recursive method:

 public static void zeroToThree(int i) {        
           if (i < 4) {             

If called as zeroToThree(0), this will print out:


***BUT*** note that this is not an appropriate use of recursion. Recursion should only be used in cases where an iterative approach would not work - and this is clearly not the case here. This is just a really simple way of showing recursion.


(Click this link if you want to go to the full notes from later on in the Java Revolution.)