How to implement recursion in Java?
How to properly implement recursion in Java? Problem with StackOverflowError
Hello everyone! I'm trying to understand recursion in Java, but I keep encountering the StackOverflowError. Please advise how to properly organize a recursive method call to avoid this?
I wrote a simple function to calculate the factorial of a number, but when the value is 10000, the program crashes. Here's my code:
public class RecursionTest {\n public static int factorial(int n) {\n if (n == 0) {\n return 1;\n }\n return n * factorial(n - 1);\n }\n\n public static void main(String[] args) {\n System.out.println(factorial(10000)); // StackOverflowError\n }\n}I've already tried:
- Increasing the stack size
No answers yet.
Log in to leave an answer