PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Recursion in Java

← All stacks

Theory

63/270

Recursion in Java

Recursion is a method calling itself. Write the base case first: if (n <= 1) return 1; then the step: return n * fact(n - 1);. No base case → StackOverflowError.

Trace fact(5) on paper: 5*4*3*2*1. Recursion uses the call stack. Deep recursion can blow memory. Some problems are clearer as loops.

Use recursion when the problem is the same shape smaller: factorial, tree walk, simple Fibonacci demo.

Let's take this on the board with one tiny Main class — no extra files. Recursion in Java — output: 120. fact(5) → 5*fact(4) → … → 5*4*3*2*1. Stop when n <= 1. Start from main, go line by line, and stop at each print. That output is the proof for Recursion.

Exam tip

Say base case first, then the recursive step. Trace fact(5).

Example

public class Main {
  static int fact(int n) {
    if (n <= 1) return 1;
    return n * fact(n - 1);
  }
  public static void main(String[] args) {
    System.out.println(fact(5)); // 120
  }
}

Recursion in Java — output: 120. fact(5) → 5*fact(4) → … → 5*4*3*2*1. Stop when n <= 1.

Short notes

  • DefRecursion = method calls itself until a base case.
  • RuleBase case first. No base → StackOverflowError.
  • Usefactorial, tree, self-similar problems.
  • RememberTrace one tiny input on paper before coding.

Questions

1

What is recursion?

2

What if there is no base case?

Previous← Wrapper Class in JavaNextCall by Value and Call by Reference in Java →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.