devxlogo

Recursion

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 toimplement 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 ");      return;    }    try {      num = Integer.parseInt(args[0]);    } catch(NumberFormatException e) {      e.printStackTrace();      return;    }    System.out.println(integerFactorial(num));  }}

devx-admin

Share the Post: