Tsallaka zuwa abun ciki
Justice Tech School

Recursion

Recursion solves a problem by calling the same method on a smaller input. Always include a base case, or the program ends with a StackOverflowError.

Example
public class Main {
  static int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
  }

  public static void main(String[] args) {
    System.out.println(factorial(5));
  }
}

Result

120

Exercise

Name the part that stops the calls.

if (n <= 1) return 1; // the  case

Quiz Test

What error appears with no base case?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.