library
beginnerMethod Overloading Rules
Know the exact rules Java uses to resolve overloaded methods and the common pitfalls with autoboxing and varargs.
Method overloading allows multiple methods with the same name but different parameter lists. The compiler resolves which to call at compile time following strict priority:
Mail sorting: exact zip code slot first, then regional bin, then state bin, then everything-else bin. Most specific match wins.
Key Concepts
1
1. Exact match — parameter types match arguments exactly.
2. Widening primitive — int to long, float to double.
3. Autoboxing/unboxing — int to Integer and vice versa.
4. Varargs — String... matches any number of arguments.
2
Each phase is tried in order; the first match wins. Within a phase, the most specific method is selected.
3
Common pitfalls: print(int) vs print(long) with argument 5 calls print(int) (exact). print(Object) vs print(String) with null calls print(String) (more specific). But adding print(Integer) makes null ambiguous — compiler error. Return type alone doesn't create valid overloads. With inheritance, the reference type determines overload selection.