</>
Skip to content
Java lessons (24/47)

Java — Recursion

Basic recursion

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

Fibonacci

public static int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Stack overflow

// Infinite recursion causes stack overflow
public static void infinite() {
    infinite();
}

Mini Practice

  1. Write factorial function
  2. Calculate fibonacci
  3. Avoid stack overflow
  4. Practice recursion

Up Next

Continue with Classes and Objects - OOP basics.

Related Topics

Frequently Asked Questions about Recursion

What is Recursion in Java?

Recursion is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Recursion?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Recursion.

Why is Recursion important in Java?

Recursion is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.