Method Overloading

Same Name, Different Parameters

Overloading means several methods with the same name but different parameter lists (number, type or order of parameters). Java picks the right one at compile time from the arguments.

Example

public class Main {
    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;
    }

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

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2.5, 3.1));
        System.out.println(add(1, 2, 3));
        System.out.println(add("Hello", "Java"));
    }
}

Output

5
5.6
6
Hello Java

What Counts as Overloading

ChangeValid overload?
different number of parametersyes
different parameter typesyes
different order of types (int, String) vs (String, int)yes
only the return type differsno, compile error
only parameter names differno, compile error

Tip: System.out.println itself is overloaded: there are versions for int, double, char, String, Object and more.