Java Method Overloading

Method overloading lets you give several methods the same name, as long as their parameter lists differ. Java figures out which version to run based on the arguments you pass. This keeps related operations under one clear, easy-to-remember name.

What overloading solves

Suppose you want to add two numbers, but sometimes they are integers and sometimes they are decimals. Without overloading you might invent separate names like addInts and addDoubles. With overloading, you can call both of them add, and Java picks the right one automatically.

Two methods, one name

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

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

  public static void main(String[] args) {
    System.out.println(add(5, 3));       // uses the int version
    System.out.println(add(5.5, 3.2));   // uses the double version
  }
}

// Output:
// 8
// 8.7

What counts as a different signature

The combination of a method's name and its parameter list is called its signature. To overload a method, the parameter lists must differ in the number of parameters, their types, or their order. The compiler uses these differences to decide which method to call.

  • Different number of parameters: add(int, int) vs add(int, int, int)
  • Different parameter types: print(int) vs print(String)
  • Different order of types: format(int, String) vs format(String, int)
Note: The return type alone does NOT distinguish overloaded methods. You cannot have int total() and double total() with identical parameter lists. The compiler would have no way to tell them apart and reports an error.

Overloading with a different count

Same name, different number of parameters

public class Main {
  static int sum(int a, int b) {
    return a + b;
  }

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

  public static void main(String[] args) {
    System.out.println(sum(2, 3));      // 5
    System.out.println(sum(2, 3, 4));   // 9
  }
}

// Output:
// 5
// 9
Method 1Method 2Valid overload?
add(int, int)add(double, double)Yes, types differ
sum(int, int)sum(int, int, int)Yes, count differs
show(int, String)show(String, int)Yes, order differs
int get()double get()No, only return type differs
Note: A great real-world example lives in the standard library: System.out.println is overloaded so you can pass it an int, a double, a String, a boolean, and more. That is why one method name handles every type you throw at it.

Exercise: Java Method Overloading

What is required for two methods with the same name to be a legal overload?