Intermediate Java Day 4: Methods & Recursion

Goal of this Day

Today you will learn:

By the end, you will be able to write recursive methods and understand how recursion works in Java.

Step 1: Method Overloading

Method overloading allows you to have multiple methods with the same name but different parameters.


public static int add(int a, int b) {
    return a + b;
}

public static double add(double a, double b) {
    return a + b;
}

Explanation:

Step 2: Recursion Basics

A recursive method calls itself until a base condition is met.


public static int factorial(int n) {
    if(n == 0) return 1;
    return n * factorial(n - 1);
}

System.out.println(factorial(5)); // 120

Explanation:

Step 3: Recursive Algorithms

Factorial


public static int factorial(int n) {
    if(n == 0) return 1;
    return n * factorial(n - 1);
}

Fibonacci


public static int fibonacci(int n) {
    if(n == 0) return 0;
    if(n == 1) return 1;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Step 4: Tail Recursion & Stack Limits

Tail recursion is a type of recursion where the recursive call is the last operation.

Example (factorial tail recursion):


public static int factorialTail(int n, int result) {
    if(n == 0) return result;
    return factorialTail(n - 1, n * result);
}

Note:

Practice


public static int factorial(int n) {
    if(n == 0) return 1;
    return n * factorial(n - 1);
}

System.out.println(factorial(5)); // 120

Exercise

Write a recursive method to calculate the nth Fibonacci number.

Steps:

Example:


public class Fibonacci {
    public static int fibonacci(int n) {
        if(n == 0) return 0;
        if(n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String[] args) {
        System.out.println(fibonacci(10)); // 55
    }
}