Java/Recursion

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
Concepts of Object Oriented Programming
How to Setup Java on your PC
Introduction to Applets
View Applet in a web browser
Data Types, Variables,and Arrays
Operators
Control Statements
Packages, Classes, and Interfaces
Inheritance and Polymorphism
Strings
Recursion
Random Numbers
Exception Handling
Java IO and file Handling
Java Thread and Multithreading
Java Collections
Java Network Programming
Image, Audio, Video
Advanced Java
Generics
AWT
Swing
Regular Expression
JDBC
XML and Java

Recursion is a mechanism available in most programming languages. In some of problem context recursion is the best solution and even good programmers start thinking recurrsively. Recursion is mainly calling the same functionality with itself. It will call itself until any criteria is matched or it went till the bottom of something. Recursion also helps when you traverse a graph or a tree in data structures. One of the good examples of recurrsion is to find out the factorial of a number.

public class RecursionExample {
 
  public static void main(String[] args) {
 
    long num = 5;
    long fact = 0;
    fact = factorial(num);
 
    System.out.println(num + "! = " + fact + ".");
 
  }
 
  public static long factorial(long n) {
 
    if (n <= 1) {
      return 1;
    }
    else {
      return n * factorial(n - 1);
    }
  }
 
}

As you can see in the above example factorial() is being called within itself again till the criteria is matched. It works like this that the inner most call it evaluated first. In the above example factorial method will be called 5 times.

1. factorial(5);

2. factorial(4);

3. factorial(3);

4. factorial(2);

5. factorial(1);

Since factorial(1) is inner most call it will be evaluated first. Then factorial(2) will be evaluated then factorial(3) and factorial(4). In the last factorial(5) will be evaluated and the results will be combined like in the RecursionExample.