Creating Recursive Methods

Methods

Creating Recursive Methods

🙋 Need help? Ask an expert now!

In Java, recursion is a programming technique in which a method calls itself to calculate a result. This method is an efficient way to solve problems with only a few lines of code. Take a look at the example of recursion below and figure out what it does.

RecursiveMethodsExample.java
package exlcode;

public class RecursiveMethodsExample {

  public static void main(String[] args) {
    // prints 1-10 in descending order
    print(10);
  }

  public static void print(int parameterOne) {
    if (parameterOne > 0) {
      System.out.print(parameterOne + " ");
      parameterOne--;
      // recursive call
      print(parameterOne);
    }
  }
}

Recursion means that within the course of the method body, there is a statement that calls the same method as the method it belongs in. To prevent a repeating loop from occurring, every recursive method has a "base case" which exits the method when the method is complete.

In the method above, the base case is the if statement because the method will stop when parameterOne is less than 0. Let's track what happens when the method is called.

  1. print(10);

  2. System.out.println(10 + " ");

  3. parameterOne--;

  4. print(9);

  5. System.out.println(9 + " ");

  6. print(8);

    and so on until the boolean expression in the if statement evaluates to false.

Edit Me on GitHub!

Application Question

#!exl::repl('index.prob.repl.yaml')