Recursion in Java

Recursion is the process when a function calls itself, directly or indirectly. Recursion is just like a function but it made a self function call.

It is mostly avoided by the developers because it may lead to having an unconditional loop and hence can be caused to get StackOverflow error.

Using recursion we can make a conditional loop that will be executed until the given condition gets false.


Below program use recursion, to calculate factorial of any number –

public class Demo {

	public int fact(int number) {
		if (number == 0)
			return 1;
			return number * fact(number - 1);

	public static void main(String[] args) {

		Demo fact = new Demo();
		int number = 7;
		int factorial = fact.fact(number);

		System.out.println("factorial of number " + number + " is - " + factorial);

Example Output