WeCodeAcademy

Method Overloading and Recursion

Overloading lets several methods share a name when their parameters differ. Recursion is a method that calls itself.

ExampleJava
public class Main {
  static int plus(int a, int b) { return a + b; }
  static double plus(double a, double b) { return a + b; }

  static int factorial(int n) {
    if (n <= 1) return 1;       // stop condition
    return n * factorial(n - 1);
  }

  public static void main(String[] args) {
    System.out.println(plus(2, 3));
    System.out.println(plus(2.5, 3.5));
    System.out.println(factorial(5)); // 120
  }
}
Output
5
6.0
120

Every recursive method needs a stop condition (the if (n <= 1) above), otherwise it calls itself until the program crashes.

Quick check

What does every recursive method need?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.