Recursion is a technique in which a functions calls itself.

Factorial Example

Factorial is the multiplication of each numbers from 1 to N. For example 4 factorial = 4 * 3 * 2 * 1 = 24.

Let's look at the following example:


At line 11 the function calls itself but with decremented value as argument.

The recursion should eventually end which is done at line 8.

Stack Overflow Exception

Recursion must have an end condition so an endless self calling is prevented.

If not stack overflow exception is thrown.

The following example causes such:

Be careful when using recursion. It may force you to restart your computer or server if the recursion is infinite.