For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
When solving complex problems, sometimes a task can be broken down into smaller versions of the same task. Recursion in Java is a programming technique where a method calls itself to solve a part of the problem. This approach is powerful for solving mathematical computations, tree traversals, and algorithm designs.
In this blog, we’ll cover everything you need to know about Java recursion, from the basic working to programs and memory allocation.
Ready to go from Java basics to building full-stack applications? Join this Software Engineering course to learn by doing.
Recursion in Java is a technique where a method calls itself to solve a problem by breaking it down into smaller, similar subproblems. Every recursive method must have a base condition to stop further calls, or it may cause a StackOverflowError. It’s commonly used in problems like factorial, Fibonacci series, and tree traversal. Recursion uses the call stack for memory, making it powerful but memory-intensive if not used carefully.
Check out: Error vs. Exception in Java
Let's start with a simple recursion example in Java programming language.Suppose you want to calculate the sum of numbers from 1 to 5. Instead of using a loop in Java, you can define a method that calls itself to add numbers:
public class SumExample {
static int sum(int n) {
if (n == 1)
return 1;
else
return n + sum(n - 1);
}
public static void main(String[] args) {
System.out.println(sum(5)); // Output: 15
}
}
Output
15
Explanation:The method sum(n) keeps calling itself with n-1 until it reaches 1. This is a classic recursive function in Java.
Future-proof your coding career with top online programs: • Full Stack Bootcamp – upGrad • AI in Full Stack Development – IIIT Bangalore • Cloud & DevOps Certificate – upGrad
Every recursive method in Java must have a base condition to stop calling itself. Without a base condition, the recursion will continue indefinitely, leading to a stack overflow error in Java recursion.
Example of base condition:
if (n == 1) return 1;
This tells the program when to stop making further recursive calls.
Here’s how recursion in Java typically works:
In short, recursion moves deeper first (function calls stack up) and then starts resolving (unwinding the stack).
Now, let's see some important Java recursion programs.
Calculating factorial (n!) is a classic problem that fits recursion well.
public class FactorialExample {
static int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
Output:
120
Explanation:The factorial program in Java using recursion multiplies the current number with the factorial of the number before it, until it reaches 0.
The fibonacci series in Java using recursion generates a sequence where each number is the sum of the two before it.
public class FibonacciExample {
static int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int terms = 7;
for (int i = 0; i < terms; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
Output:
0 1 1 2 3 5 8
Explanation: Each term is found by adding the two preceding terms, with the first two terms as 0 and 1.
Must read: For Loop in Java
If a recursive method keeps calling itself without a base condition, the system runs out of memory and throws a StackOverflowError.
Example:
public class StackOverflowExample {
static void controlledRecursion(int count) {
if (count == 0)
return;
System.out.println("Recursion count: " + count);
controlledRecursion(count - 1);
}
public static void main(String[] args) {
controlledRecursion(5); // Safe recursion
}
}
Output:
Recursion count: 5
Recursion count: 4
Recursion count: 3
Recursion count: 2
Recursion count: 1
Explanation:There’s no stopping point here, causing the stack to overflow. That's why every recursive method in Java must have a termination condition.
Check out: Infinite Loop in Java
In Java recursion, every time a method calls itself, a new stack frame (memory block) is created in the call stack.
Important Note: If recursion is too deep, it can exhaust stack memory quickly, leading to a stack overflow error in Java recursion.
Some major advantages of recursion in Java are:
Simplifies complex problemsRecursion makes problems like tree traversal, graph exploration, or divide-and-conquer easier to express and solve. It provides a clean and intuitive solution for naturally recursive problems.
Natural solution for nested structuresProblems involving nested or repetitive structures (e.g., directories, hierarchical data) are more naturally handled using recursion. It offers clear and maintainable code compared to iterative methods.
Reduces code lengthRecursive functions can replace lengthy loops, especially for complex problems, reducing the overall lines of code while maintaining clarity and readability.
Ideal for backtracking problemsRecursion is perfect for problems like Sudoku, solving mazes, or generating permutations, where exploring different paths or states is required in a clear, step-by-step manner.
Despite its usefulness, recursion has downsides. Key disadvantages of recursion in Java include:
Recursion is a fundamental and powerful technique in Java programming. Understanding how recursive functions in Java work, when to use them, and the potential risks like stack overflow errors is crucial for writing efficient and safe code.
Start practicing with small Java recursion programs, and as you get comfortable, you’ll be able to apply recursion to solve more complex real-world problems elegantly!
Recursion in Java is a programming technique where a method calls itself to solve a problem in smaller subproblems. It's commonly used for tasks like factorial, Fibonacci, or tree traversal, and requires a base condition to prevent infinite loops or a StackOverflowError.
Recursion is best used when a problem can be broken into smaller, similar subproblems, such as with mathematical computations, file system traversal, or algorithms like quicksort and mergesort. It simplifies code for problems with repeated structures or nested elements.
A base case is a condition in a recursive method that stops the recursion. Without it, the method would call itself endlessly, causing a StackOverflowError. It ensures the problem reduces to a solvable case and avoids infinite recursion.
A StackOverflowError occurs when a recursive method keeps calling itself without reaching a base case, consuming all stack memory. It's a sign of infinite recursion or excessively deep recursion that the JVM stack can't handle.
Recursion uses method calls and the call stack to repeat operations, while iteration uses loops like for or while. Recursion is elegant for tree-based problems, but iteration is more memory-efficient and generally preferred for simpler loops.
Yes, recursive methods in Java can return values. For example, calculating a factorial or sum of numbers often uses return values to pass results back up the recursive call stack.
Generally, yes. Recursion can be slower due to extra overhead from multiple method calls and stack usage. Iteration is often faster and more memory-efficient, but recursion may offer cleaner solutions for certain problems.
Common real-world uses include calculating factorials, Fibonacci series, traversing directories, solving mazes, and working with data structures like trees and graphs (e.g., DFS, preorder traversal).
Yes, many recursive solutions can be rewritten using iteration, especially with the help of stacks or loops. However, some problems are naturally recursive and are more intuitive when solved that way.
To prevent infinite recursion, always define a base case that ends the recursion and ensure each recursive call moves the problem toward that base case. Also, validate input parameters to avoid unexpected infinite loops.
Tail recursion occurs when the recursive call is the last statement in the method. While Java doesn’t optimize tail recursion like some languages (e.g., Scala), using tail-recursive style can still help make the logic clearer and slightly more memory-efficient.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.