Posts

Showing posts with the label Recursion

Recursion in Java

Image
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 stat...