Explain it simply
Explain it simply
At a coffee shop you can order "a coffee", "two coffees" or "two coffees, no milk". The barista hears the same word, coffee, every time, but knows what to do from the details that follow it.
Method overloading works the same way. You can write several methods called add, such as add(int, int), add(double, double) and add(int, int, int), as long as their parameter lists differ. When you call add(5, 3), the compiler looks at how many arguments there are and their types, and picks the version that fits best. Nobody has to remember names like addInts, addDoubles and addThree.
Problem → Why → Solution
The problem: thinking a different return type is enough
A developer wants one parse() that returns an int and another that returns a double, so they write the code below. Both have the parameter list (String text), so javac refuses with "method parse(String) is already defined in class Main".
public class Main {
static int parse(String text) {
return Integer.parseInt(text);
}
static double parse(String text) { // error: already defined
return Double.parseDouble(text);
}
public static void main(String[] args) {
System.out.println(parse("42")); // which one should run?
}
}Why is this not allowed?
The compiler chooses an overload only from the arguments at the call. In parse("42") the only argument is one String, so nothing says which version you mean, and the return type cannot help when the result goes straight into println. That is why the return type is not part of the signature, and why the JDK uses separate names such as parseInt and parseDouble.
Core concept: signatures and compile-time selection
In Java a method's signature is its name plus the ordered list of parameter types, and no class may contain two methods with the same signature. Overloads must therefore differ in parameter count (add(int, int) vs add(int, int, int)), in type (add(int, int) vs add(double, double)) or in order (f(int, String) vs f(String, int)). The return type, the parameter names and whether the method is static are not part of the signature, so changing only those does not create an overload.
Which overload runs is decided at compile time, not while the program runs. The compiler looks at the declared (static) types of the argument expressions and searches in three phases. Phase one allows only exact matches and primitive widening such as int to long or double, with no boxing and no varargs. Only if that finds nothing does phase two allow boxing and unboxing between int and Integer, and only then does phase three consider varargs (int...). That is why add(5, 2.5) widens 5 to 5.0 and picks add(double, double).
If more than one overload fits within a phase, the compiler picks the most specific one: with describe(Object) and describe(String), describe("hi") gets the String version. If none is most specific, you get "reference to f is ambiguous". Crucially, the choice uses the argument's declared type, not the object's type at runtime: with Object x = "hi"; describe(x); the Object version runs.
Do not confuse overloading with overriding. Overloading adds new methods with the same name but different signatures, and the choice happens at compile time. Overriding means a subclass replaces a parent method that has the exact same signature, and the choice happens at runtime based on the object; the Inheritance lesson covers it. Constructors can be overloaded by these same rules, which the Constructors lesson puts to use.
- Collect every method with that name
- Try exact types and widening
- Else allow boxing and unboxing
- Else allow varargs
- Pick the most specific or fail
As soon as a phase finds a match, later phases are never considered.
General pattern
static Result name(TypeA a) { ... } // one parameter
static Result name(TypeA a, TypeB b) { ... } // different count
static Result name(TypeB b, TypeA a) { ... } // different order
static Result name(TypeC c) { ... } // different type
static Result name(TypeA... many) { ... } // varargs, chosen last
// NOT an overload: only the return type differs
static Other name(TypeA a) { ... } // compile errorEvery overload shares the name and has a different list of parameter types. Changing only the return type is an "already defined" error. The compiler considers a varargs version last.
Example: three add() overloads
This program has three methods named add. For each of the four calls in main, predict which version the compiler picks; the last one, add(5, 2.5), is the one most people get wrong at first. In the output, notice that int results such as 8 print without a decimal point while double results such as 7.5 have one.
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;
}
public static void main(String[] args) {
System.out.println(add(5, 3));
System.out.println(add(2.5, 4.2));
System.out.println(add(1, 2, 3));
System.out.println(add(5, 2.5)); // 5 is widened to 5.0
}
}Code breakdown
- Two ints
System.out.println(add(5, 3));Both arguments are int, so add(int, int) is an exact match. add(double, double) would also fit through widening, but the int version is more specific, so it wins and prints 8.
- Two doubles
static double add(double a, double b) {2.5 and 4.2 are double literals, and Java never narrows a double to an int automatically, so this is the only version that fits. The result is 6.7.
- Different count
static int add(int a, int b, int c) {Only this three-parameter version can accept add(1, 2, 3). A different parameter count is the clearest way to tell overloads apart.
- Mixed int and double
System.out.println(add(5, 2.5)); // 5 is widened to 5.0add(int, int) cannot take 2.5. add(double, double) fits in phase one by widening 5 to 5.0, so the result is 7.5.
8
6.7
6
7.5Widening, boxing, varargs: which comes first
The program below has show(long), show(Integer) and show(int...). For show(5) it is tempting to think boxing int 5 into an Integer is closer, but widening int to long belongs to phase one, so the long version wins. Calls with two arguments or none can only be accepted by the varargs version. The final three describe() calls show selection by declared type.
public class Main {
static void show(long x) { System.out.println("long " + x); }
static void show(Integer x) { System.out.println("Integer " + x); }
static void show(int... xs) { System.out.println("varargs " + xs.length); }
static void describe(Object o) { System.out.println("Object version"); }
static void describe(String s) { System.out.println("String version"); }
public static void main(String[] args) {
show(5); // phase 1: widening int -> long beats boxing
show(5, 6); // only varargs accepts two ints
show(); // only varargs accepts zero arguments
Object x = "hello";
describe(x); // declared type is Object
describe("hello"); // declared type is String
describe(null); // String is more specific than Object
}
}| Call | Chosen method | Reason |
|---|---|---|
| show(5) | show(long) | Widening comes before boxing |
| show(5, 6) | show(int...) | Only varargs fits |
| describe(x) | describe(Object) | x is declared as Object |
| describe(null) | describe(String) | String is more specific |
In real projects
Where this shows up in real projects
The JDK itself uses overloading everywhere. System.out.println() has around ten overloads for int, double, char, String, Object and more, so you just call println whatever the type. Math.max() and Math.abs() have int, long, float and double versions, and List.of() has fixed-parameter overloads for zero to ten elements plus a varargs version for anything longer.
In your own code the most common use is convenience overloads that fill in defaults: sendEmail(to, subject) calls sendEmail(to, subject, "no-reply@shop.com"). Java has no default parameters, so this pattern takes their place. A famous trap is List<Integer>: list.remove(1) picks remove(int index) and deletes the element at index 1, not the value 1. To delete the value you must write list.remove(Integer.valueOf(1)) to reach remove(Object). Plenty of production bugs started right there.
Common mistakes
Common mistakes
1. Changing only the return type or parameter names
static int add(int a, int b) and static double add(int x, int y) share the signature add(int, int), so javac reports "method add(int,int) is already defined". Change a parameter type, or give the method a different name such as addExact.
2. Designing overloads that make calls ambiguous
With f(int a, double b) and f(double a, int b), the call f(1, 2) fits both with one widening each, neither is more specific, and you get "reference to f is ambiguous". Avoid overloads that differ only in the order of convertible types.
3. Expecting the runtime type to choose the overload
Object x = "hi"; describe(x); is expected to call describe(String). The overload was already chosen at compile time from the declared type, Object, so the Object version runs. Choosing by runtime type is the job of overriding and polymorphism, covered in later lessons.
Best practices
Best practices
- Every overload should do the same conceptual job; if the jobs differ, use different names.
- Let shorter overloads delegate to the fullest version so the logic lives in one place.
- Avoid overloads at the same position with convertible types such as int and Integer or Object and String.
Mini challenge
Mini challenge: receipt label overloads
Write three label() overloads and one varargs sum() for a coffee-shop receipt. The shorter overloads must call the full version instead of formatting on their own.
- label(String item, int quantity, double unitPrice) returns a String like "Cake x3 @ 2500.0 = 7500.0"
- label(String item, int quantity) calls the full version with DEFAULT_PRICE (1000.0)
- label(String item) calls the two-parameter version with quantity 1
- sum(int... amounts) returns 0 when called with no arguments
public class Main {
static final double DEFAULT_PRICE = 1000.0;
// TODO: label(String item, int quantity, double unitPrice)
// -> "Cake x3 @ 2500.0 = 7500.0"
// TODO: label(String item, int quantity) -> delegate with DEFAULT_PRICE
// TODO: label(String item) -> delegate with quantity 1
// TODO: sum(int... amounts) -> total of all amounts, 0 when empty
public static void main(String[] args) {
// TODO: print label("Tea"), label("Coffee", 2), label("Cake", 3, 2500.0)
// TODO: print sum() and sum(1500, 2500, 800)
}
}Expected: Tea x1 @ 1000.0 = 1000.0 Coffee x2 @ 1000.0 = 2000.0 Cake x3 @ 2500.0 = 7500.0 No items: 0 Bill: 4800
Show hint
Inside the method, the varargs parameter int... amounts is an int[] you can loop over with for-each. label("Tea") calls label("Tea", 1), which in turn calls label("Tea", 1, DEFAULT_PRICE): a chain.
Show solution
public class Main {
static final double DEFAULT_PRICE = 1000.0;
static String label(String item, int quantity, double unitPrice) {
double total = quantity * unitPrice;
return item + " x" + quantity + " @ " + unitPrice + " = " + total;
}
static String label(String item, int quantity) {
return label(item, quantity, DEFAULT_PRICE);
}
static String label(String item) {
return label(item, 1);
}
static int sum(int... amounts) {
int total = 0;
for (int amount : amounts) {
total += amount;
}
return total;
}
public static void main(String[] args) {
System.out.println(label("Tea"));
System.out.println(label("Coffee", 2));
System.out.println(label("Cake", 3, 2500.0));
System.out.println("No items: " + sum());
System.out.println("Bill: " + sum(1500, 2500, 800));
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Signature = method name + ordered parameter types; the return type and parameter names are not included.
- Overloads must differ in parameter count, type or order.
- The compiler picks at compile time from declared types: exact/widening, then boxing, then varargs.
- If no overload is most specific the call is ambiguous, and the runtime object type never changes the choice.