Core Java Fundamentals ยท Methods

Method Overloading

Several methods can share a name if their parameters differ. Java picks the right one from the arguments you pass.

OverloadingDemo.java

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

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

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

    public static void main(String[] args) {
        int two = add(1, 1);
        double half = add(0.25, 0.25);
        int three = add(1, 1, 1);
        System.out.println(two + " " + half + " " + three);
    }
}

Step by step

  1. add(1, 1): two ints, so Java picks add(int, int).
  2. add() has finished, so its variables are gone.
  3. The value it returned, 2, is stored in two.
  4. add(0.25, 0.25): two doubles, so add(double, double) runs.
  5. add() has finished, so its variables are gone.
  6. The value it returned, 0.5, is stored in half.
  7. Three ints: add(int, int, int).
  8. add() has finished, so its variables are gone.
  9. The value it returned, 3, is stored in three.
  10. It prints 2 0.5 3.
  11. Three methods, one name. Java matched each call to the right version by its arguments: 2, 0.5 and 3.