Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Jul 27, 1998

Recursion

Question:
Is it possible to make recursive subroutine calls in Java?

Answer:
Yes, you can make recursive method calls in Java. Just make sure you have a termination condition to avoid infinite recursion and stack overflows. The following is an example of recursion in Java. It implements a recursive factorial function. Note that in "real life" you wouldn't want to implement the factorial function recursively. It is more efficient to implement it iteratively.

public final class Recursion {

  // Keep in mind you would never want to implement a recursive factorial
  // routine because it is grossly inefficient as compared to an iterative
  // computation.
  public static final int integerFactorial(int num) {
    if(num <= 1) {
      if(num < 0)
	throw new IllegalArgumentException("Factorial undefined for values less than 0");
      return 1;
    }
    return num * integerFactorial(num - 1);
  }

  public static final void main(String args[]) {
    int num;

    if(args.length != 1) {
      System.err.println("usage: Recursion ");
      return;
    }

    try {
      num = Integer.parseInt(args[0]);
    } catch(NumberFormatException e) {
      e.printStackTrace();
      return;
    }

    System.out.println(integerFactorial(num));
  }

}

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date