Java Recursion
Java Tutorial » Java Recursion Method
A Java method that calls itself is known as a recursive method. Recursion may be it is a little difficult to understand. The best way to figure out how it works is to experiment with it.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
//code to be executed
methodname();//calling same method
}
Makes the code compact but complex to understand.
Factorial of a Number Using Recursion example
We have a method named factorial(). The factorial() is called from the main() method. with the number variable passed as an argument.
Example
4 factorial = 120
class Factorial {
static int factorial( int x ) {
if (x != 0) // termination condition
return x * factorial(x-1); // recursive call
else
return 1;
}
public static void main(String[] args) {
int number = 5, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}
Output:static int factorial( int x ) {
if (x != 0) // termination condition
return x * factorial(x-1); // recursive call
else
return 1;
}
public static void main(String[] args) {
int number = 5, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}
4 factorial = 120
java recursion example, exercices, stack, factorial, not working, out of memory, missing return statement, practice problems, return value
java recursion example, exercices, stack, factorial, not working, out of memory, missing return statement, practice problems, return value
Java Recursion - java
Online Editor
This tool makes it easy to create, adjust, and experiment with custom colors for the web.
HTML Templates

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.
CSS HTML Layout

Find here examples of creative and unique website layouts.
Free CSS HTML Menu

Find here examples of creative and unique website CSS HTML menu.