Recursion in Java with Example – Programming Tutorial for Beginners (original) (raw)
Recursion is one of the tough programming techniques to master. Many programmers working on both Java and other programming languages like C or C++ struggles to think recursively and figure out the recursive pattern in the problem statement, which makes it is one of the favorite topics of any programming interview. If you are new to Java or just started learning Java programming language and you are looking for some exercise to learn the concept of recursion then this tutorial is for you.
In this programming tutorial, we will see a couple of examples of recursion in Java programs and some programming exercise that will help you to write recursive code in Java-like calculating Factorial, reversing String, and printing Fibonacci series using the recursion technique.
For those who are not familiar with the recursion programming technique here is the short introduction: "Recursion is a programming technique on which a method calls itself to calculate result".
It's not as simple as it looks and mainly depends upon your ability to think recursively. One of the common traits of recursive problems is that they repeat themselves, if you can break a big problem into small junk of repetitive steps then you are on your way to solving it using recursion.
Also, knowledge of essential data structure is also very important and that's why I suggest all Java programmers one of these comprehensive Data structures and Algorithms courses to fill the gaps in your understanding.
How to solve a problem using Recursion in Java
In order to solve a problem using recursion in Java or any other programming language e.g. C or C++, You must be able to figure out :
The base case, the last point which can be resolve without calling recursive function e.g. in the case of the Fibonacci series it is 1 and 2 where the result will be 1. In the case of a recursive power function, it's zero power which is equal to 1, or in the case of calculating Factorial its factorial of zero which is equal to 1.
With every recursive method call, Your problem must reduce and approach the base case. If this is not the case then you won't be able to calculate the result and eventually die with java.lang.StackOverFlowError
1. Recursion Programming Example in Java
In our programming example of recursion in Java, we will calculate the Fibonacci number of giving lengths using recursion. In the case of the Fibonacci number, the current number is the sum of the previous two numbers except for the first and second number which will form the base case for the recursive solution.
public class RecursionTest {
public static void main(String args[]) {
System.out.println("fibonacci series for length 1 is " + fibonacci(6));
}
public static int fibonacci(int number){
if(number < 1){
throw new IllegalArgumentException("Invalid argument for Fibonacci series: "
+ number);
}
//base case of recursion
if(number == 1 || number == 2){
return 1;
}
//recursive method call in java
return fibonacci(number-2) + fibonacci(number -1);
}
}
If you look above example of recursion in Java you will find that we have a base case where the program returns a result before calling the recursive function and then with every invocation, the number is decreased by 1. This is very important to reach a solution using the recursive technique.
2. Programming Exercise to solve using Recursion
Here are few more programming exercises to learn the Recursion programming techniques in the Java programming language. These Recursion based exercises are solely for practicing and building your code sense. In order to understand Recursion properly, you must try to think recursive e.g. look at a tree as a collection of small trees, look at string as collecting of small String, look at staircases as a collection of the small staircase,s, etc.
Anyway, try to solve the following programming exercise by using the Recursion programming technique for better understanding
1. Print Fibonacci series in Java for a given number, see here for a solution
2. Calculate factorial of a given number in Java, sees here for solution of this programming exercise
3. Calculate the power of a given number in java
4. Reverse a String using recursion in Java, see here for a solution
5. Find out if there is a loop in a linked list using recursion
This was a simple introduction of the Recursion programming technique to Java programmers with the most basic examples. There is a lot more to learn on Recursion including different types of recursion e.g. tail recursion, improving the performance of the recursive algorithm using memoization or caching the pre-calculated result, etc.
It is also recommended not to use the recursive method in production code instead write iterative code to avoid any StackOverflow error.
Other programming tutorials from Javarevisited Blog