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)); }}