Let’s learn recursion in java.
recursion in java
recursion is a process where a method calls itself infinitely or endlessly.
recursion program in java
recursion makes a java code closely packed. Here’s an example on infinite recursive function.
public class InfiniteRecursiveExample { static void print() { System.out.println("helloworld"); print(); } public static void main(String[] args) { print(); } }
Output:
helloworld
helloworld
helloworld
helloworld………
java.lang.StackOverflowError
Now let’s see an example on finite recursive function.
public class FiniteRecursiveExample { static int number = 0; static void print() { number++; if(number <= 10) { System.out.println("helloworld " + number); print(); } } public static void main(String[] args) { print(); } }
Output:
helloworld 1
helloworld 2
helloworld 3
helloworld 4
helloworld 5
helloworld 6
helloworld 7
helloworld 8
helloworld 9
helloworld 10
Also read – major features of java