Skip to main content

Java For Python Programmers Edition 2

Section 7.3 Recursion Limits: Python vs. Java

When using recursion, both Python and Java have practical limits on how deep the recursion can go before running into errors. This is due to the way both languages manage something called the call stack, which is a limited amount of memory used to keep track of function or method calls.
The consequence of running out of call stack space, is a concept you may have already encountered in Python. Java handles this in a very similar way to Python, both throwing an error when the call stack depth is exceeded. The only difference is the name of the error:
  • In Python, overflowing the call stack raises a RecursionError error.
  • In Java, it throws a StackOverflowError.

Aside

In both languages, if you write a recursive function that doesn’t have a base case or that just recurses too deeply, you’ll eventually hit this limit. When this happens, Python will raise a RecursionError, while Java will throw a StackOverflowError. This is because both languages use a call stack to keep track of function calls, and when the stack runs out of space, it results in an error. Hence, when an algorithm might require thousands of recursive calls, an iterative, loop-based, approach is likely going to be the preferred solution in both Python and Java.
The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError due to overflowing the call stack.
The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError.
You have attempted of activities on this page.