Recursion in Java
What is recursion? The simple answer; it’s when a method calls itself. But, how does this happen? And why?
As you know, a method is a block of code that only executes when it is called. But if inside that method was another call to the method itself, a sort of loop affect is created. Recursion is another way to make a loop.
Let’s look at an example:
public class MyClass {static void myMethod(int i) { System.out.println(i); i++; if(i < 10) { myMethod(i); } }
public static void main(String[] args) {myMethod(0);
} }
In this example, we have a method named ‘myMethod‘ with a parameter list of (int i). Down in the main part of this program, we made a call to the method only once, supplying an argument of 0, which the method stores in int i. But inside the method, after printing the value of int i and increasing it by 1, we have an ‘if‘ statement.
If the current value of int i is less than 10, we make a new call to ‘myMethod‘, now supplying the updated value of int i as an argument.
Because the new call to ‘myMethod‘ came from inside the body of ‘myMethod‘, we say the method called itself. And this is recursion.
The output of this program is:
0 1 2 3 4 5 6 7 8 9
Just remember when making a recursive loop to have a conditional check that can end the loop. Otherwise, you end up with a method that has endless recursion.
Comments
Post a Comment