What is meant by Recursion in java? || Explain recursion with example in java || Java recursion: Recursive method



Recursion:

Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. When a method calls itself, new local variables and parameters are allocated storage on the stack, and the method code is executed with these new variables from the start. A recursive call does not make a new copy of the method. Only the arguments are new. As each recursive call returns, the old local variables and parameters are removed from the stack, and execution resumes at the point of the call inside the method. Recursive versions of many routines may execute a bit more slowly than the iterative equivalent because of the added overhead of the additional function calls. Many recursive calls to a method could cause a stack overrun. Because storage for parameters and local variables is on the stack and each new call creates a new copy of these variables, it is possible that the stack could be exhausted. If this occurs, the Java run-time system will cause an exception.

Example:
class Factorial
{
static long calcFactorial(long value)
{
if(value == 0) return 1;
else
return calcFactorial(value - 1) * value;
}
public static void main(String args[])
{
System.out.println("Factorial of 4 : " + calcFactorial(5));
}
}

Example

class Recursion
{
static void printOdd(int a)
{
System.out.println(a);
a++;
if(a <= 10)
printEven(a);
}
static void printEven(int b)
{
System.out.println(b);
b++;
if(b <= 10 )
printOdd(b);
}
public static void main(String args[])
{
printOdd(1);
}
}

1 Comments

Please do not enter any spam link in the comment box

  1. thanks for sharing this nice topic of java programming language. I would like to share this nice and easy topic of java programming language. And please keep it up.
    Thank you.


    Subscribe me on YouTube

    ReplyDelete

Post a Comment

Please do not enter any spam link in the comment box