Java Method Overloading and Varargs

Overloading means many methods with the same name but different parameters (different number or different types). Java chooses the right one from the arguments you give.

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));           // int version
        System.out.println(add(2.5, 3.5));       // double version
        System.out.println(add(1, 2, 3));        // three parameters
        System.out.println(add("Java", "25"));   // String version
    }
}
Output

5
6.0
6
Java25

Rules

  • The parameter list must be different (number, type or order of the types).
  • A different return type alone is not enough.
  • Java picks the closest match, and widens types when it needs to (an int can go into a long parameter).
public class Same {
    static int value() { return 1; }
    static double value() { return 1.0; }   // only the return type is different

    public static void main(String[] args) {
        System.out.println(value());
    }
}
Output

Same.java:3: error: method value() is already defined in class Same
static double value() { return 1.0; } // only the return type is different
^
1 error
error: compilation failed

Real use

The Java library is full of overloading. System.out.println() has a version for every type: int, char, double, String, boolean and Object.

Varargs: any number of arguments

Write three dots after the type. Inside the method the parameter is an array:

public class Varargs {
    static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) {
            total += n;
        }
        return total;
    }

    static void show(String label, int... values) {     // varargs must be last
        System.out.println(label + ": " + values.length + " values");
    }

    public static void main(String[] args) {
        System.out.println(sum());
        System.out.println(sum(5));
        System.out.println(sum(1, 2, 3, 4));
        show("Marks", 70, 80, 90);
    }
}
Output

0
5
10
Marks: 3 values

  • A method can have only one varargs parameter, and it must be the last one.
  • String.format() and List.of() are well known methods with varargs.
Note: Overloading is decided when the code is compiled, by the types you write. Overriding (in inheritance) is decided when the program runs. Next: Java Recursion.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.