Notes

  • A recursive method is basically a method that calls itself. It usually contains a case that halts recursion and another that continues recursion.
  • Each recursive call has its own local variables, and parameter values check the progress of a recursion process.
  • A recursion is essentially another form of iteration.
  • Recursion is typically used to traverse through Strings, arrays, and ArrayLists.
  • A merge sort utilizes a divide and conquer algorithm to sort ArrayLists. It first divides the ArrayList into halves, then calls itself in both halves to sort them, and finally combines them when they are sorted.
  • Recursion trees are used to visualize each recursive case for recursion code.
  • There are 2 main cases in recursion. The base case serves as the lowest level condition for which recursion will halt. The recursive case continuously calls the method itself at lower levels until the base case is reached.
public class Recursion {
    public int fac(int num) {
        if (num == 1) {
            return 1;
        } else {
            return num * fac(num - 1);
        }
    }

    public static void main(String[] args) {
        Recursion myObj = new Recursion();
        System.out.println("1! = " + myObj.fac(1));
        System.out.println("2! = " + myObj.fac(2));
        System.out.println("3! = " + myObj.fac(3));
        System.out.println("4! = " + myObj.fac(4));
    }
}

Recursion.main(null);
1! = 1
2! = 2
3! = 6
4! = 24