«Back to Home

Core Java

Topics

Recursion In Java

Recursion
 
Recursion in Java is a procedure where a method calls itself continuously. A method that calls itself is called recursive method in Java.
 
In other words, recursion is the process of defining something in terms of itself. Recursion is an attribute, which allows a method to call itself. A method that calls itself is said to be recursive in Java.
 
Syntax

returntype methodname(){
//code
methodname();//calling same method
}
 
Let’s see an example of recursion, given below.
 
Code
  1. public class RecursionTest {  
  2.     static void display() {  
  3.         System.out.println("Recursion");  
  4.         display();  
  5.     }  
  6.     public static void main(String[] args) {  
  7.         display();  
  8.     }  
  9. }  
16

Output

17

Infinite times……………
 
Let’s see an example of recursion, given below.
 
Code
  1. public class RecursionTest {  
  2.     static int count = 0;  
  3.     static void msg() {  
  4.         count++;  
  5.         if (count <= 10) {  
  6.             System.out.println("Java " + count);  
  7.             msg();  
  8.         }  
  9.     }  
  10.     public static void main(String[] args) {  
  11.         msg();  
  12.     }  
  13. }  


Output

19

Finite times…….
 
Let’s see an example of recursion, given below.
 
Code
  1. public class RecursionTest {  
  2.     static int factorial(int n) {  
  3.         if (n == 1) {  
  4.             return 1;  
  5.         } else {  
  6.             return (n * factorial(n - 1));  
  7.         }  
  8.     }  
  9.     public static void main(String[] args) {  
  10.         System.out.println("Factorial of 8 is: " + factorial(8));  
  11.     }  
  12. }  
20

Output

21

Factorial number……
 
Let’s see an example of recursion, given below.
 
Code
  1. public class RecursionTest {  
  2.     static int n1 = 0, n2 = 1, n3 = 0;  
  3.     static void fibon(int count) {  
  4.         if (count > 0) {  
  5.             n3 = n1 + n2;  
  6.             n1 = n2;  
  7.             n2 = n3;  
  8.             System.out.print(" " + n3);  
  9.             fibon(count - 1);  
  10.         }  
  11.     }  
  12.     public static void main(String[] args) {  
  13.         int count = 10;  
  14.         System.out.print(n1 + " " + n2); //printing 0 and 1        
  15.         fibon(count - 2); //n-2 because 2 numbers are already printed       
  16.     }  
  17. }  
23

Output

24

Fibonacci series……….
 
Summary

Thus, we learnt that recursion in Java is a procedure in which a method calls itself continuously and also learnt how we can create a program, using recursion in Java.