Recursion in java

Let’s learn recursion in java.

Recursion in java

Recursion is a process where a method calls itself infinitely or continuously.

Recursion program

Recursion makes code closely packed and difficult to understand. Here’s an example on infinite recursive function.

public class InfiniteRecursiveExample
{
   static void print()
   {  
      System.out.println("helloworld");  
      print();  
   }
   public static void main(String[] args)
   {
      print();
   }
}


Output:

helloworld
helloworld
helloworld
helloworld………
java.lang.StackOverflowError


Now let’s see an example on finite recursive method.

public class FiniteRecursiveExample
{
   static int number = 0;
   static void print()
   {
      number++;
      if(number <= 10)
      {  
         System.out.println("helloworld " + number);  
         print();  
      }
   }
   public static void main(String[] args)
   {
      print();
   }
}


Output:

helloworld 1
helloworld 2
helloworld 3
helloworld 4
helloworld 5
helloworld 6
helloworld 7
helloworld 8
helloworld 9
helloworld 10


Fibonacci using recursion : recursion example

public class JavaFibonacciRecursion
{
   static int num1 = 0, num2 = 1, num3 = 0;
   static void displayFibonacciSeries(int count)
   {      
      if(count > 0)
      {      
         num3 = num1 + num2;      
         num1 = num2;      
         num2 = num3;      
         System.out.print(" " + num3);     
         displayFibonacciSeries(count - 1);      
      }      
   }
   public static void main(String[] args)
   {
      int count = 10;
      System.out.print(num1 + " " + num2);      
      displayFibonacciSeries(count - 2);
   }
}


Output:

0 1 1 2 3 5 8 13 21 34


Factorial using recursion : recursion example

public class JavaFactorialRecursion
{
   static int printFactorial(int number)
   {   
      if(number == 1)
      {
         return 1;
      }
      else
      {
         return(number * printFactorial(number - 1));      
      }
   }
   public static void main(String[] args)
   {
      System.out.println("Factorial of 6 is : " + printFactorial(6));
   }
}


Output:

Factorial of 6 is : 720


Also read – major features of java