Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 201 ยท Methods

Method Overloading

Learn Java method overloading - the rules, how the compiler picks an overload through widening, boxing and varargs, ambiguous calls, and the list.remove(int) trap.

Suppose you need methods that compute the larger of two int values, of two double values and of three int values. Without overloading you'd invent names like maxInt, maxDouble and maxOfThree. Java lets you give them all the same name, max, as long as their parameter lists differ. This is method overloading, and you've relied on it from day one: IO.println prints an int, a String or a double because there are many println methods with different parameter types.

Overloading is resolved entirely by the compiler. At each call it looks at the argument types and picks the best matching method. Usually that's obvious. Sometimes, when conversions such as widening, autoboxing and varargs come into play, the choice is surprising or the compiler refuses to choose at all. This lesson covers the rules for declaring overloads, the exact steps Java uses to resolve a call, ambiguity errors, and the real-world traps that come from overloading.

Declaring overloads

Two methods in the same class overload each other when they have the same name and different signatures. The signature is the method name plus the number, types and order of its parameters:

Java One name, several methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The parameter lists can differ in:

  • the number of parameters: max(int, int) and max(int, int, int);
  • their types: max(int, int) and max(double, double);
  • their order, if the types differ: pad(String, int) and pad(int, String). This is legal but confusing, so avoid it.

What doesn't count:

  • The return type alone. int parse(String s) and double parse(String s) can't coexist. A call like parse("5"); whose result is ignored would give the compiler no way to choose. The error is method parse(String) is already defined.
  • Parameter names. area(int width, int height) and area(int side, int count) have the same signature area(int, int).
  • Modifiers like static, final on parameters, or access modifiers.
  • Generic type arguments. sum(List<Integer>) and sum(List<Double>) clash, because generics are erased at compile time (Type Erasure).

Overloads may have different return types, access modifiers and throws clauses, as long as their parameter lists differ.

Overloading is not overriding. Overloading means several methods with the same name and different parameters, chosen at compile time by argument types. Overriding means a subclass replaces an inherited method with the same signature, chosen at run time by the object's actual class. You'll meet overriding in Polymorphism and Method Overriding.

Overloading in the standard library

Overloads are everywhere in the JDK, usually for one of three reasons:

  • Different types, same idea: Math.abs(int), abs(long), abs(float), abs(double); String.valueOf for every primitive.
  • Optional arguments. Java has no default parameter values, so methods offer short and long forms: substring(begin) and substring(begin, end); Arrays.sort(a) and Arrays.sort(a, from, to).
  • Convenience inputs: String.join(", ", "a", "b") and String.join(", ", list).

The optional-argument pattern is easy to write yourself. The short version fills in the default and calls the full version, so the logic lives in one place:

Java Overloads as default arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

How Java picks an overload

When a call matches several overloads, the compiler resolves it in three phases, and stops at the first phase that finds any applicable method:

  1. Exact match or widening only. Primitive widening (int to long, float to double, char to int, ...) and subclass-to-superclass conversion are allowed. No boxing, no varargs.
  2. Boxing and unboxing allowed. int can become Integer, Integer can become int.
  3. Varargs allowed. A method like log(String... parts) is considered only now.

Within the winning phase, if several methods apply, Java picks the most specific one: the method whose parameter types could be passed to all the others. int is more specific than long, String more specific than Object.

These phases exist for backward compatibility: when boxing and varargs were added in Java 5, old code had to keep calling the same methods as before. The consequence is that widening beats boxing, and boxing beats varargs:

Java Widening beats boxing beats varargs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at show(number). Your intuition might say int is "closer" to Integer, but phase 1 already finds show(long) through widening, so boxing is never even considered. The text(null) call shows "most specific" at work: null can be a String or an Object, and String wins because every String is also an Object.

Ambiguous calls

If the winning phase has several applicable methods and none is more specific than all the others, the compiler reports an ambiguity error. Two classic examples:

Java
void pair(int a, double b)  { }
void pair(double a, int b)  { }

pair(1, 2);
// error: reference to pair is ambiguous
//   both method pair(int,double) in Main and method pair(double,int) in Main match

pair(1, 2) fits both by widening one argument, and neither method is more specific: (int, double) can't be passed to (double, int) or the other way around. The fix is to make the call explicit, for example pair(1, 2.0), or to redesign the overloads.

Java
void find(Integer id)   { }
void find(String name)  { }

find(null);
// error: reference to find is ambiguous
//   both method find(Integer) in Main and method find(String) in Main match

null fits any reference type, and Integer and String are unrelated, so neither is more specific. A cast picks one: find((String) null). This error often appears when someone adds a new overload to an existing method, which can break callers that passed null.

Java Resolving an ambiguity with a cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Remove the // before find(null); and press Run to see the ambiguity error for yourself.

Real-world traps

Overloading is resolved from the static (declared) types of the arguments, at compile time. That's where the surprises come from.

list.remove(int) vs list.remove(Object)

List<E> has two remove methods: remove(int index) removes by position, and remove(Object o) removes a matching element. With a List<Integer>, an int argument picks remove(int) in phase 1, without boxing:

Java Removing from a List of Integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When you mean "remove this value", box it explicitly with Integer.valueOf(...). This bug ships to production surprisingly often, because both calls compile without a warning.

Overloads chosen by declared type

Because resolution uses the declared type, an Object variable holding a String still goes to the Object overload:

Java
void describe(Object o) { IO.println("an object"); }
void describe(String s) { IO.println("a string"); }

Object thing = "hello";
describe(thing);           // prints "an object": thing is declared as Object
describe("hello");         // prints "a string"

If you need behavior that depends on the actual class at run time, use overriding (Polymorphism) or pattern matching (Pattern Matching), not overloading.

Printing a char array

System.out.println has an overload for char[] that prints the characters, while every other array goes to println(Object) and prints a type and hash code:

Java
char[] letters = { 'h', 'i' };
int[] numbers = { 1, 2 };
System.out.println(letters);              // hi
System.out.println(numbers);              // [I@... (type and hash code)
System.out.println("letters: " + letters); // letters: [C@... (concatenation uses toString)

The third line surprises people: string concatenation converts the array with toString(), so the char[] overload is never involved.

Designing good overloads

  • Same name, same meaning. All overloads should do the same thing with different input forms. If they do different things, give them different names (findById, findByName), which also removes any chance of ambiguity with null.
  • Delegate to one implementation. Short overloads should fill in defaults and call the full one, as repeatWord does.
  • Avoid overloads with the same number of parameters whose types are related by widening or boxing (long vs Integer, int vs double in swapped positions). Readers can't predict which one is called.
  • Be careful mixing overloads with varargs. A varargs overload is chosen only when nothing else fits, which can be confusing; see Varargs.
  • Consider a record or builder when you'd need many overloads for many optional parameters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pair of methods can NOT coexist in one class?

    Methods can't differ only in return type, because the signature (name plus parameter types) is the same. The other pairs differ in parameter count, types or order.
  2. 2. Given void f(long x) and void f(Integer x), what does f(7) call?

    Phase 1 allows only widening, and int widens to long, so f(long) is found and boxing is never considered.
  3. 3. For List<Integer> list = new ArrayList<>(List.of(5, 6, 7));, what is list after list.remove(1);?

    An int argument matches remove(int index) without boxing, so the element at index 1 (6) is removed. Use list.remove(Integer.valueOf(1)) to remove a value.
  4. 4. Given void g(Object o) and void g(String s), what does Object x = "hi"; g(x); call?

    Overload resolution happens at compile time using static types. x is declared as Object, so g(Object) is chosen regardless of the actual object.
  5. 5. Given void h(Integer i) and void h(String s), what happens with h(null)?

    null fits both parameter types, and Integer and String are unrelated, so neither overload is more specific. A cast like h((String) null) resolves it.

Summary

  • Overloaded methods share a name but have different parameter lists (number, types or order); the return type, parameter names and modifiers don't count.
  • Java has no default arguments; short overloads that delegate to a full one serve the same purpose.
  • The compiler resolves a call in three phases: widening only, then boxing/unboxing, then varargs; the first phase with a match wins, and the most specific method in it is chosen.
  • When no method is most specific, the call is ambiguous and doesn't compile; a cast or a more precise argument fixes it.
  • Overloads are chosen from declared types at compile time, which explains traps like list.remove(int) vs remove(Object).
  • Give overloads one shared meaning; use different names when the behavior differs.

Next: Variable Scope, where you'll learn exactly where each variable is visible and how long it lives.