Overloading with Autoboxing and Varargs
What You'll Learn
You'll learn how Java decides which overloaded method to call when autoboxing and varargs come into play.
The Precedence Rules
When you overload methods and call them with arguments, Java follows a strict priority order to find the best match:
- Exact match (no conversion needed)
- Primitive widening (e.g.,
inttolong) - Autoboxing (e.g.,
inttoInteger) - Varargs (variable-length arguments)
This hierarchy prevents ambiguity. Java always prefers "cheaper" conversions before more expensive ones.
Why This Matters
Consider these overloaded methods:
void process(int x) { } // Exact match
void process(long x) { } // Widening
void process(Integer x) { } // Autoboxing
void process(int... x) { } // Varargs
When you call process(42), Java picks the exact match first. If that didn't exist, it would try widening to long. Only if widening fails would it try autoboxing to Integer. Varargs is the last resort.
The Varargs Rule
Varargs is always considered least specific because it's the most flexible—it can accept zero or more arguments. Java only selects a varargs method when no other match is possible.
void print(Integer x) { }
void print(int... values) { }
print(5); // Calls print(Integer x) via autoboxing, not varargs!
Even though 5 could be packed into the varargs array, autoboxing happens first.
Combining Rules
Java never combines autoboxing with widening in a single step. You can't directly pass an int to a method expecting a Long—there's no int → long → Long chain.
Key Takeaway: When overloading with autoboxing and varargs, Java prefers exact matches, then primitive widening, then autoboxing, and finally varargs as the last resort. Understanding this precedence prevents confusing compilation errors and unexpected method calls.