STEM-TutorLearn • Practice • ExcelBook Free DemoFree demo

Recursion in Java, explained for AP Computer Science A

A recursive method is a method that calls itself. In AP Computer Science A you mostly need to read and trace recursive code, and recursion questions are a reliable source of multiple-choice marks once the method clicks.

On this page
  1. The idea
  2. Example: factorial
  3. How to trace a recursive method
  4. Worked examples
  5. A tracing checklist
  6. Recursive binary search
  7. Recursion or a loop?
  8. Common mistakes
  9. Practice questions
  10. Frequently asked questions
  11. Key takeaways
  12. Related guides

The idea

Recursion solves a problem by reducing it to a smaller version of the same problem. To count the steps on a staircase, you could say: “the number of steps is one plus the number of steps left after the first one”. Each time, the problem shrinks, until you reach the bottom, where the answer is obvious: zero steps remain.

Every correct recursive method has two parts:

If there is no base case, or the input never gets closer to it, the calls never stop. Java eventually runs out of memory for the calls and throws a StackOverflowError.

Example: factorial

The factorial n! is n × (n − 1) × … × 1, and 0! = 1. Recursively, n! = n × (n − 1)!.

public static int factorial(int n)
{
    if (n == 0)
    {
        return 1;                    // base case
    }
    return n * factorial(n - 1);     // recursive case
}

How to trace a recursive method

Each call waits for the call it makes to finish. Picture the calls as a stack of plates: each new call goes on top, and results come back down the stack in reverse order. For factorial(4):

factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 * factorial(0)
factorial(0) = 1                 (base case)

Now substitute back up: factorial(1) = 1, factorial(2) = 2, factorial(3) = 6, factorial(4) = 24. On the exam, write this trace in the margin. It turns a confusing question into simple arithmetic.

Worked examples

Example 1: sum of digits

What does digitSum(472) return?
public static int digitSum(int n)
{
    if (n < 10)
    {
        return n;
    }
    return n % 10 + digitSum(n / 10);
}

Example 2: reversing a string

What does rev("code") return?
public static String rev(String s)
{
    if (s.length() <= 1)
    {
        return s;
    }
    return rev(s.substring(1)) + s.substring(0, 1);
}

Example 3: output order

What does mystery(3) print?
public static void mystery(int n)
{
    if (n > 0)
    {
        mystery(n - 1);
        System.out.print(n + " ");
    }
}

Example 4: counting calls

How many times is factorial called, in total, when you call factorial(5)?

Example 5: two recursive calls

What does fib(5) return?
public static int fib(int n)
{
    if (n <= 1)
    {
        return n;
    }
    return fib(n - 1) + fib(n - 2);
}

A tracing checklist

When a multiple-choice question shows a recursive method, work through the same four checks. First, find the base case and note what it returns. Second, see how the argument changes in each call, and confirm it moves towards the base case. Third, notice whether any work, such as printing or adding, happens before or after the recursive call. Fourth, write out the calls in a column and substitute the returned values back up. This routine is quick, and it avoids the guesswork that costs marks on recursion questions.

Binary search finds a value in a sorted array by checking the middle element and discarding half the array each time. It is naturally recursive: search the left half or the right half, which is a smaller version of the same problem.

public static int search(int[] arr, int target, int low, int high)
{
    if (low > high)
    {
        return -1;                          // not found
    }
    int mid = (low + high) / 2;
    if (arr[mid] == target)
    {
        return mid;
    }
    else if (target < arr[mid])
    {
        return search(arr, target, low, mid - 1);
    }
    else
    {
        return search(arr, target, mid + 1, high);
    }
}

Each call halves the range, so even an array of a million elements needs only about 20 comparisons. Merge sort uses the same divide-and-conquer idea: split the array in half, sort each half recursively, then merge.

Recursion or a loop?

Anything written recursively can also be written with a loop. Factorial and digit sums are simpler as loops in real programs. Recursion shines when a problem naturally splits into smaller copies of itself, such as searching sorted data, sorting, or exploring tree-like structures such as folders inside folders. For the AP exam, the key skill is reading recursive code accurately.

Common mistakes

Practice questions

Try each one before opening the answer.

Q1. What does factorial(5) return?

Show answer
120.

Q2. What does digitSum(9005) return?

Show answer
5 + 0 + 0 + 9 = 14.

Q3. A method f(n) returns n + f(n - 2) for n > 0, and 0 otherwise. What is f(6)?

Show answer
6 + 4 + 2 + 0 = 12.

Q4. What happens if you call factorial(-1) with the code above?

Show answer
n never reaches 0, so it recurses forever and throws a StackOverflowError.

Frequently asked questions

Is recursion on the revised AP Computer Science A exam?

Recursion is still in the course in the 2025–26 revision, with a focus on tracing recursive methods and on recursive searching and sorting. Check the current Course and Exam Description on AP Central for the exact scope.

Will I have to write recursive code on the free-response section?

Free-response questions rarely require recursion. You are far more likely to meet it in multiple-choice questions that ask what a recursive method returns or prints.

Key takeaways