Recursion in Java programming language
Recursion in Java programming language
In this tutorial, we will discuss the concept of Recursion in the Java programming language.
In this post, we will learn about the recursive method and how it functions in Java.
We have already discussed recursive function in C language, C++ and Python language.
Recursion in Java
Recursion is a technique in Programming languages. In Java, a method that calls on itself is called a recursive method (same concept of recursive function in C, C++ and Python);
Example of recursive function
The flow of control of recursive function:
The diagram shows how recursion works:
In the above diagram, initially, recursive() method is called from the inside of the main method (looks like a normal method call).
The recursive() method is called from the inside the same method (it called itself),
The recursion follows until a condition is fulfilled.
Program 1
class Find_Fact{ static int factorial(int num){ if (num!=0) return num*factorial(num-1); //recursive call else return 1; } public static void main(String args[]){ int number=5,fact; fact=factorial(number); System.out.println("Factorial of "+number+" is "+fact); } }
When the above code is executed, it produces the following results
Factorial of 4 is 24
In the above program, first, the factorial() method is called from inside the main method and also argument is passed.
When the value is passed to the function, it is stored in the num variable.
Initially, the argument is passed thus the value of num is 4. Then the method calls on itself which reduces the value of num by 1 and it becomes 3. Then, it passes on during the next recursive call of “factorial()” function. subsequently, it continues to reduce by one in every stage until it becomes 1.
When the num variable becomes less then 1, “if condition” returns as false and flow of control moves to Else part for execution.
once Else part executes, it excludes itself from the function.
The following picture shows how the above program is functioning
Advantages of recursion in Java:
Easy to understand, readable code and reduced number of lines in the program.
This recursion makes complex tasks easy and flexible. Also, repeated functioning is easier following iterations.
Disadvantages of recursion in Java
Tracing and debugging are very difficult.
Every recursive step lacks a separate memory location hence extra memory is required process (becomes very slow).
Similar post
Suggested for you