Method recursion
Method recursion is when a method calls itself. This might at first seem like something that happens by mistake but is an efficient technique for solving some programming problems.
Here is some code that shows a recursive method in its most basic form:
void recursiveMethod() { recursiveMethod(); }
If we call the recursiveMethod
method, its only line of code will then call itself, which will then call itself, which will then call itself, and so on. This process will go on forever until the app crashes, giving the following error in Logcat:
java.lang.StackOverflowError: stack size 8192KB
When the method is called, its instructions are moved to an area of the processor called the stack, and when it returns, its instructions are removed. If the method never returns and yet more and more copies of the instructions are added, eventually the stack will run out of memory (or overflow) and we get StackOverflowError
.
We can attempt...