Java Method Overloading
What is Method Overloading?
Method overloading lets you define multiple methods that share the SAME name but differ in their parameter list — a different number of parameters, different parameter types, or a different order of parameter types. Java figures out which version to run based on the arguments you pass at the call site.
Different Number of Parameters
public static int add(int a, int b) {
return a + b;
}
public 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));
}5 9
Different Parameter Types
public static double add(double a, double b) {
return a + b;
}
public static String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2.5, 1.5));
System.out.println(add("Hello, ", "world!"));
}4.0 Hello, world!
Different Order of Parameter Types
public static void display(String label, int value) {
System.out.println(label + ": " + value);
}
public static void display(int value, String label) {
System.out.println(value + " -> " + label);
}
public static void main(String[] args) {
display("Score", 95);
display(95, "Score");
}Score: 95 95 -> Score
Resolved at Compile Time
The compiler decides exactly which overloaded version to call by looking at the number and types of the arguments in your source code — before the program ever runs. This is called static (or compile-time) dispatch.
Ambiguous Overloads Won't Compile
If the compiler can't figure out a single best match — for example, because of automatic widening between numeric types — your code simply fails to compile with an "ambiguous method call" error.
public static void show(long a, double b) {
System.out.println("long, double version");
}
public static void show(double a, long b) {
System.out.println("double, long version");
}
public static void main(String[] args) {
show(5, 5); // ambiguous: both ints can widen either way — won't compile
}Overloading vs Overriding (Preview)
Aspect | Overloading | Overriding |
Method name | Same name, different parameters | Same name, same parameters |
Where it happens | Within the same class (or via inheritance) | In a subclass, replacing a superclass method |
Resolved | At compile time (static dispatch) | At runtime (dynamic dispatch) |
Return type | Can differ | Must be the same or a covariant subtype |
Purpose | Offer several convenient ways to call similar logic | Customize inherited behavior for a specific subclass |
Practice Exercises
Write three overloaded versions of a multiply method: (int, int), (double, double), and (int, int, int).
Write an overloaded printInfo method that accepts either a single String, or a String and an int, and prints them differently.
Deliberately write two overloads that create an ambiguous call with mixed numeric types, observe the compiler error, then fix it with an explicit cast.