Java Recursion

A method can call itself to perform similar operation on remaining elements of a set or resultants operation in current method call. This process is called recursion and java also support recursion. Java recursion is a tricky way to divide a larger problem into smaller tasks and solve them one by one.

Java recursion example

Multiplication of two numbers is an easy task but multiplication of a range of number is a complex one. We can use recursion to divide this task into small pieces and solve. In following example we will do simple multiplication of of two numbers but with an additional trick that the resultant number will be passed to next call of same method as follows:


public class RecursionExample {
public static void main(String[] args) {
int result = multiply(1,10);
System.out.println(result);
}
public static int multiply(int first, int last) {
if (last >=first) {
int result = last * multiply(first, last-1);
return result;
} else {
return 1;
}
}
}

multiply() function multiply a ranges of numbers starting from first number to last number. It takes two parameters, firs and last. last number is multiplied by resultant of another function call multiply() with difference that it is passed first number as it is but last number decremented by one. multiply() will be called recursively until the next recursive call of multiply() is passed same number as first and last number. Understanding of recurstion is still a bit complex therefore it is suggested to place a debugging point in some advance java IDE like Netbeans and debug the file instead of simply running the file, execute the code line by line and check the value of result variable in multiply() function.

Note: There must be a stopping / halting condition in recursive function otherwise the function will behave like an infinite loop and will never end. In above example we are checking that first is greater than last only then next recursive call is issued otherwise a value is simply returned (1 in this case).