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 <= 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));  }}
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist