Recursion in Java

Overview

When we call a method inside a same method that is recursion. Following is a simple example of recursion.
 public class RecursionDemo {
public static void main(String[] args) {
sayHi();
}

// The reason why we marked this method as static because we want to call this method in a static method that is main()
private static void sayHi() {
System.out.println("Hi!");
sayHi(); // This recursion will throw a StackOverflowError.
}
}
To handle a recursion you got to have an exit strategy / condition.
 public class RecursionDemo {
public static void main(String[] args) {
// sayHi();
sayHello(3);
}

// The reason why we marked this method as static because we want to call this method in a static method that is main()
private static void sayHi() {
System.out.println("Hi!");
sayHi(); // This recursion will throw a StackOverflowError.
}

private static void sayHello(int count) {
System.out.println("Hello");
if (count <= -1) {
return;
}
sayHello(count - 1);
}
}

Reference

Comments

Popular posts from this blog

Collections in Java

Exception Handling

OOPS Concept in Java