Labs ICT
โญ Pro Login

Method Overloading

What if you want a method that works with different kinds of input? Say you want an add method that works with two integers, but also with three integers, and also with doubles. Do you have to come up with different names for each one?

Nope. Java lets you define multiple methods with the same name as long as their parameters are different. This is called method overloading.

Same Name, Different Parameters

Java figures out which method to call based on the arguments you pass. The number of parameters or their types must be different.

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

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

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

Calling add(2, 3) runs the first version with two parameters. Calling add(2, 3, 4) runs the second. Java knows which one you mean by looking at what you passed.

Different Types

You can also overload by changing the parameter types, not just the count.

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(2, 3));
    System.out.println(add(2.5, 3.7));
  }
}

The first call uses integers and runs the int version. The second call uses doubles and runs the double version. Same method name, different types.

Method overloading is everywhere in Java. System.out.println itself is overloaded โ€” it works with strings, numbers, booleans, everything. Under the hood, there are multiple println methods with different parameter types.

๐Ÿงช Quick Quiz

What is method overloading?