Warning. Stack Overflow

[comp1110-7P]

When using Recursion, your program might crash with a very long Stack Trace, and the specific exception is java.lang.StackOverflowError:

Exception in thread "main" java.lang.StackOverflowError at Program.overflow(Program.java:3) at Program.overflow(Program.java:3) at Program.overflow(Program.java:3) at Program.overflow(Program.java:3) at Program.overflow(Program.java:3) at Program.overflow(Program.java:3) [... many more identical lines ...]

Essentially, your computer has some limited amount of space in its memory to store your stack frames, and when you have run out, a stack overflow happens, usually crashing your program.

This is usually because you got something wrong in writing your recursive code, and so your program loops forever, but with recursion, it eventually runs out of space. Make sure that your inputs to your recursive call are different (and "smaller") from the arguments to the current function!

Another possible reason is that you did write the recursive code correctly, but are operating on a data structure that is too large. This can happen, though you will usually not encounter such cases early in a computing degree. There are ways to increase the size reserved for stack frames, though it is not necessarily guaranteed that that will be a good solution. When working with large data, you might have to switch to iteration. However, don't see this as a reason to never use recursion - premature optimisation is never a good idea!

bars magnifying-glass caret-down plus minus arrow-right xmark