Recursion

Recursion allows a method to call itself.

The following code is an example of recursion. It calculates the factorial numbers.

 
class Factorial {
  // this is a recursive function
  int fact(int n) {
     int result;

    if (n == 1)
      return 1;
    result = fact(n - 1) * n;
    return result;
  }
}

public class Main {
  public static void main(String args[]) {
    Factorial f = new Factorial();

    System.out.println("Factorial of 5 is " + f.fact(5));

  }
}

The output from this program is shown here:


Factorial of 5 is 120
Home 
  Java Book 
    Class  

Methods:
  1. Syntax for Method Creation
  2. Recursion
  3. Method with Parameters
  4. Pass-by-value vs Pass-by-reference
  5. What is Methods Overloading
  6. The main() Method
  7. Using Command-Line Arguments with main method
  8. Subclasses and Method Privacy