Java Tutorial

Java Recursion

A recursive method calls itself with a smaller problem. Every recursion needs a base case — without one, the call stack grows until it crashes.

Call yourself — with a way out

Recursion solves a problem by reducing it to a smaller version of the same problem. The base case is the stop condition that returns without calling again. Miss it, and you get aStackOverflowError.

Example — factorial

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

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

Countdown shows the stack

Each call waits for the next to finish. Printing before and after the recursive call makes the unwind visible: the "after" lines run on the way back up.

Example

public class Main {
  static void countdown(int n) {
    if (n < 0) return;
    System.out.println("down " + n);
    countdown(n - 1);
    System.out.println("up " + n);
  }

  public static void main(String[] args) {
    countdown(3);
  }
}

Sum an array recursively

Another classic pattern: process the head, then recurse on the rest. An index (or a shrinking length) tracks how much work is left.

Example

public class Main {
  static int sumFrom(int[] nums, int i) {
    if (i >= nums.length) return 0;
    return nums[i] + sumFrom(nums, i + 1);
  }

  public static void main(String[] args) {
    int[] nums = { 2, 4, 6 };
    System.out.println(sumFrom(nums, 0));   // 12
  }
}

Many recursive solutions have a simple loop equivalent. Prefer recursion when the problem is naturally nested (trees, divide-and-conquer). Prefer a loop when you only need to walk a list once — it uses less stack.

Try It Yourself

Exercise: Write static int sumTo(int n) that returns 1 + 2 + ... + nusing recursion. Base case: n <= 0 returns 0.

Show solution
public class Main {
  static int sumTo(int n) {
    if (n <= 0) return 0;
    return n + sumTo(n - 1);
  }

  public static void main(String[] args) {
    System.out.println(sumTo(4));   // 10
  }
}

Each call adds n and asks for the sum of the smaller prefix until the base case returns 0.

Key Takeaways

  • A recursive method calls itself with a smaller problem.
  • Always include a base case that stops the recursion.
  • Each call uses stack space; infinite recursion ends in StackOverflowError.
  • Use recursion for nested structure; use loops for flat iteration when either works.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Maths

Recursive factorial

n! = n × (n−1)!. The base case stops the chain at 0 or 1. Recursion mirrors the definition on the page.

n! = n × (n−1)!

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));
  }
}

Biology

Branching cell count

Each generation doubles. A recursive call models one more division until the depth limit.

N = 2ⁿ

Example

public class Main {
  static int cells(int gen) {
    if (gen == 0) return 1;
    return 2 * cells(gen - 1);
  }

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

FAQ: Java Recursion

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java recursion examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java recursion in this Java Java lesson (Java Recursion).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.