Method overloading
Overloading means several methods share a name but take different parameters:
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;
}
static double add(double a, double b) {
return a + b;
}
static String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3)); // 5
System.out.println(add(2, 3, 4)); // 9
System.out.println(add(2.5, 1.25)); // 3.75
System.out.println(add("Code", "MIRAI")); // CodeMIRAI
}
}The compiler picks the version whose parameters match the arguments, by number and then by type. You've been using overloading since your first program: System.out.println has versions for int, double, char, String and more.
What counts as different
Overloads must differ in the number, types or order of types of their parameters. A different return type alone isn't enough:
static int parse(String s) { ... }
static double parse(String s) { ... } // error: the same parameter listGiven parse("5"), the compiler would have no way to choose.
The closest match wins
public class Main {
static void show(int x) { System.out.println("int: " + x); }
static void show(long x) { System.out.println("long: " + x); }
static void show(double x) { System.out.println("double: " + x); }
public static void main(String[] args) {
show(5); // int: an exact match
show(5L); // long
show(5.0); // double
byte b = 5;
show(b); // int: a byte widens to the nearest larger type
float f = 2.5f;
show(f); // double: a float widens to double
}
}With no exact match, Java widens the argument to the nearest larger type that has a version.
Overloads instead of default values
Java has no default parameter values. Overloads fill the gap:
public class Main {
static String greet(String name, String greeting) {
return greeting + ", " + name + "!";
}
static String greet(String name) {
return greet(name, "Hello"); // reuse the full version
}
public static void main(String[] args) {
System.out.println(greet("Asha"));
System.out.println(greet("Leo", "Good morning"));
}
}The short version calls the full one, so the real logic lives in one place.
Varargs: any number of arguments
public class Main {
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
public static void main(String[] args) {
System.out.println(sum()); // 0
System.out.println(sum(4)); // 4
System.out.println(sum(1, 2, 3, 4)); // 10
}
}int... numbers accepts any number of int arguments, which arrive as an array. A varargs parameter must come last. String.format and printf work this way.