Method overloading & overload resolution
Same name, different parameter lists — and how the compiler chooses the winner.
Overloading: one name, many signatures
Two methods in the same class may share a name as long as their parameter lists differ (in number, type, or order of parameters). The return type alone is not enough — that is a compile error:
static void print(int n) { System.out.println(n); }
static void print(String s) { System.out.println(s); }
static void print(int a, int b) { System.out.println(a + ", " + b); }
The compiler selects the most specific applicable overload using a three-phase lookup:
- Exact match — no conversion. Always preferred.
- Widening primitive conversion — e.g.
byte→int,int→long. - Autoboxing / unboxing — e.g.
int→Integer. - Varargs — considered last.
Phase 1 always wins over phase 2, which wins over phase 3, which wins over phase 4. If two overloads are equally specific at the same phase, the compiler reports an ambiguity error rather than picking arbitrarily.