Recursion in Java

In this article you will learn about Recursion in Java, when you need to use recursion and how you can use it.

Recursion in Java

Let’s start exploring the concept.

What is Recursion ?

Recursion is a process in which the method call itself continuously and the method which calls itself repeatedly is called as recursive method.

How does Recursion work ?

From the definition it is clear that in recursion the function call itself continuously to get the result. And the recursive call stops at a point when it fails to satisfy the condition. So, you need to provide a condition as per your requirement to stop the recursive call else it will be continued infinite times.

Recursion in Java

Example:

Let’s print “BtechGeeks is Best” 10 times by using recursion.

Program: 

public class Main 
{  
    //declared a static integer variable count and initialized it to 1
    static int count=1;
    
    //driver method
    public static void main(String args[]) 
    {  
    //calling a user defined method printMessage()
    printMessage();  
    } 

    //Body of printMessage() method
    static void printMessage()
    {  
        //condition to stop recursive calling
        //Message needs to be printed 10 times, so used one if condition.
        if(count<=10)
        {  
            System.out.println("BtechGeeks is Best");
            //incrementing count value after printing the message once
            count++;
            //Recursively calling the same method
            printMessage();  
        }  
    }  
}
Output:

BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best
BtechGeeks is Best

When Recursion can be used ?

There are multiple instances when you can go for the use of recursion concept. Mainly it depends on your problem that you want to solve. For example when you want to solve a complicated problem and it is little difficult to solve it through iterative approach then you can break it down and modularize it by using recursion and then you can solve it very easily.

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Related Java Programs: