You are on page 1of 5

RECURSION IN JAVA

 A method that calls itself is known as a recursive method.


And, this technique is known as recursion.
 How recursion works?
 Public static void main(String args[]){
………….
recurse()
… ….. …..
}
Static void recurse() {
recurse()
}
 In the above program, recurse() method is called from inside the
main method at first (normal method call).
 Also, recurse() method is called from inside the same
method, recurse(). This is a recursive call.
 The recursion continues until some condition is met to prevent it
from execution. If not, infinite recursion occurs.
 Hence, to prevent infinite recursion, if...else statement (or
similar approach) can be used where one branch makes the
recursive call and other doesn't.
class Factorial {

static int factorial( int number ) {


if (number != 0)
return number * factorial(number-1); // recursive call
else
return 1;
}

public static void main(String[] args) {


int number = 4, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}
Advantages and Disadvantages of Recursion
 When a recursive call is made, new storage location for variables
are allocated on the stack.
 As, each recursive call returns, the old variables and parameters
are removed from the stack. Hence, recursion generally use more
memory and are generally slow.
 On the other hand, recursive solution is much simpler and takes
less time to write, debug and maintain.

You might also like