Recursive Methods in Java

In Java, methods can call themselves; this is called recursion and is an efficient and elegant way of working with methods. Recursive methods in Java facilitate and structure our work in larger programs.

What is Recursive Methods in Java?

A recursive method in Java is a method that is defined by having references to itself; that is, the method calls itself. Using recursive methods is a common programming technique that can create a more efficient and more elegant code. Further, a recursive method always contains a base condition, also called the trivial case, which indicates the end of the recursion and which therefore does not call itself.

 

 

A recursive method in Java is a method that calls itself

 

 

Recursive methods in Java,

  • is a reference to itself
  • always contains a base condition
  • can handle direct and indirect calls
  • commonly used in programming and mathematics.

Base Condition, Direct- and Indirect recursion

Some terms that are good to be familiar with when working with recursive methods are:

 

  • Base condition: A recursive method must always have a base case. The base condition is the trivial case that indicates when the recursion is complete.
  • Direct Recursion: A method that calls itself.
  • Indirect call: A method that calls another method, which in turn calls the first method again. Note that indirect calls, for this reason, is often difficult to get an overview.

Example – Declaring a Recursive method in Java

 

Let´s declare a recursive method that sums all the integers between 1 and N.

  • First, we check the base condition, that is, if N is equal to one. In this case, there is no need to call the method again. Therefore, the recursion will not be needed in this case.
  • However, if N is greater than N, the method will call itself until all we summed all the integers.

 

private static int summa (int N) { 
    // Support variable
    int sum;                     

    // Base condition
    if (N == 1) {                
        sum = 1;
    }
    else {
        //The method calls itself -> Recursive call
        sum = N + summa(N - 1);  
    }
    return sum;                  
}

 

The code above provides the following case,

 

public static void main(String[] args) {

    // Print the sum of all integers between 1 and 4
    System.out.println(summa(4));   

    // Print the sum of all integers between 1 and 10
    System.out.println(summa(10));

    // Base condition
    System.out.println(summa(1)); 
}

 

Resulting in,

 

10
55
1

 

Moreover, the image below is an illustration of how the method works when N = 3.

Recursive Methods in Java