Java Method Recursion

In this chapter you will learn:

  1. What is Java Method Recursion
  2. Example - Java Method Recursion

Description

Recursion allows a method to call itself.

Example

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;//from  w  w w.  j av  a 2  s . c  o  m

    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:

Next chapter...

What you will learn in the next chapter:

  1. What are the four types of nested class