Sub topic 9
Overload resolution: widening, boxing and varargs
This chapter assumes you know Java's primitive types, basic class and method syntax, and how autoboxing converts between int and Integer. It covers how the compiler picks one method when several overloads could accept a call, and why boxing sits low in the priority order.
Why overload resolution matters for wrappers
When you call show(5), the compiler must choose among every method named show that could accept the argument. With primitives and wrappers in play, several overloads can be applicable at once. 5 is an int. It can widen to long, box to Integer, or box and then widen to Object.
The compiler does not guess and does not pick the "closest" type by a single rule. It follows a fixed sequence of phases defined in the Java Language Specification (JLS 15.12.2). Knowing the phases lets you predict the result, and it explains several surprises, such as List.remove in the collections chapter.
The three phases
The compiler tries three phases in order. It stops at the first phase that finds at least one applicable method.
- Phase 1: strict invocation. Allows identity conversions, primitive widening, and reference widening (subtyping). No boxing or unboxing, and no varargs.
- Phase 2: loose invocation. Allows everything from phase 1, plus boxing and unboxing (optionally followed by widening). Still no varargs.
- Phase 3: variable arity invocation. Allows everything from phase 2, and lets a method declared with
...receive a variable number of arguments.
If a phase finds several applicable methods, the compiler picks the most specific one. If no single method is most specific, the call is ambiguous and compilation fails. If no phase finds a method, compilation fails with "no suitable method".
Widening beats boxing
The first example from the topic shows the rule in its simplest form.
public class OverloadPhases {
static void show(long x) { System.out.println("long"); }
static void show(Integer x) { System.out.println("Integer"); }
static void show(Object x) { System.out.println("Object"); }
public static void main(String[] args) {
show(5); // long: widening is tried before boxing
show(Integer.valueOf(5)); // Integer: exact match
show(5.0); // Object: double boxes to Double, then widens to Object
}
}Walk through each call.
show(5): the argument is anint. In phase 1,show(long)applies becauseintwidens tolongwithout boxing.show(Integer)andshow(Object)need boxing, so they are not considered yet. Phase 1 finds one method, so the answer islong.show(Integer.valueOf(5)): the argument is already anInteger. In phase 1,show(Integer)applies by identity, andshow(Object)applies by reference widening.show(long)does not apply, because unboxing is not allowed in phase 1. Two methods are applicable, andIntegeris more specific thanObject, soIntegerwins.show(5.0): adoublecannot narrow tolongand does not matchInteger. Phase 1 finds nothing. In phase 2,doubleboxes toDouble, which widens toObject. Onlyshow(Object)applies.
This ordering exists for backward compatibility. Code written before Java 5 had no boxing, so its overloads must keep their meaning after boxing was added. If boxing had the same priority as widening, existing calls could silently change target.
Boxing beats varargs
Variable arity is the last resort. A method with int... is only considered when no fixed-arity method applies in phases 1 and 2.
public class VarargsPhase {
static void print(int... values) { System.out.println("varargs"); }
static void print(Integer value) { System.out.println("Integer"); }
public static void main(String[] args) {
print(1); // Integer: phase 2 (boxing) wins over phase 3 (varargs)
print(1, 2); // varargs: no fixed-arity method accepts two arguments
print(); // varargs: zero arguments
}
}print(1) has two candidates. Phase 1 finds nothing, because print(Integer) needs boxing and print(int...) needs variable arity. Phase 2 allows boxing and finds print(Integer). The search ends there, and the varargs method is never considered.
This rule is useful to know when you add a varargs overload next to an existing method. The old calls keep resolving to the old method.
The compiler does not unbox and then widen in the wrong order
Conversions in phase 2 are limited to specific combinations. These are allowed:
- Boxing, optionally followed by reference widening.
inttoIntegertoObjectorNumber. - Unboxing, optionally followed by primitive widening.
Integertointtolong.
These are not allowed:
- Primitive widening followed by boxing.
inttolongtoLongis not a legal conversion. - Boxing to a different wrapper.
intcannot becomeLongorDoubleby boxing.
The second rule produces a common compile error.
public class WideningThenBoxing {
static void takesLong(Long x) { System.out.println("Long"); }
static void takesNumber(Number n) { System.out.println("Number"); }
public static void main(String[] args) {
takesNumber(5); // works: int boxes to Integer, which is a Number
takesLong(5L); // works: long boxes to Long
// takesLong(5); // does not compile: int cannot box to Long
takesLong((long) 5); // works: cast first, then box
}
}An int literal can box only to Integer. If a method wants Long, give it a long value (5L) or cast.
Most specific method
When one phase finds several applicable methods, the compiler picks the most specific. Method A is more specific than method B if every call that A accepts could also be passed to B.
public class Specificity {
static void f(Object o) { System.out.println("Object"); }
static void f(Number n) { System.out.println("Number"); }
static void f(Integer i) { System.out.println("Integer"); }
public static void main(String[] args) {
f(1); // Integer: phase 2, three candidates, Integer is the most specific
f(1.5); // Number: Double boxes, Number is more specific than Object
f("text"); // Object: only f(Object) applies
}
}f(1) does not find a match in phase 1, because int is not a reference type. Phase 2 boxes it to Integer, which fits all three methods. Integer is a subtype of Number, which is a subtype of Object, so f(Integer) is the most specific.
Ambiguity arises when two methods are each better for a different parameter.
public class Ambiguity {
static void g(int a, Integer b) { System.out.println("int, Integer"); }
static void g(Integer a, int b) { System.out.println("Integer, int"); }
public static void main(String[] args) {
g(1, Integer.valueOf(2)); // int, Integer: only the first applies in phase 1
// g(1, 2); // does not compile: reference to g is ambiguous
}
}For g(1, 2), phase 1 finds nothing. In phase 2, both methods apply, each needing one boxing. Neither is more specific, so the compiler reports ambiguity. You must disambiguate with a cast or a wrapper value, such as g(1, (Integer) 2).
Overloads with null
The literal null has no type of its own, and it can be passed to any reference parameter. Phase 1 handles it, because it needs no boxing.
public class NullArgument {
static void h(Object o) { System.out.println("Object"); }
static void h(Integer i) { System.out.println("Integer"); }
public static void main(String[] args) {
h(null); // Integer: the most specific applicable overload
h((Object) null); // Object: the cast fixes the static type
}
}If the two overloads were h(Integer) and h(String), the call h(null) would be ambiguous, because neither type is a subtype of the other.
Why the static type decides
All of these decisions use the compile-time type of the argument, not the runtime type of the object.
public class StaticTypeDecides {
static void kind(Object o) { System.out.println("Object"); }
static void kind(Integer i) { System.out.println("Integer"); }
public static void main(String[] args) {
Object o = Integer.valueOf(9);
kind(o); // Object: the variable's declared type is Object
kind((Integer) o); // Integer: the cast changes the static type
}
}This is the same mechanism that makes list.remove(1) and list.remove(Integer.valueOf(1)) behave differently on a List<Integer>. The int argument finds remove(int index) in phase 1, and the Integer argument finds remove(Object) in phase 1 as well. Boxing is never needed to reach either, so the choice follows the argument's declared type directly.
Practical guidance
- When you design overloads, avoid pairs that differ only by a primitive and its wrapper, or by two different wrappers. They force callers to know the phase rules.
- Do not overload a method with both
longandIntegerparameters, or withint...and a wrapper parameter. Use distinct method names. - When a call resolves unexpectedly, check the static type of each argument, then replay the three phases.
- Use a cast or a typed local variable to select a particular overload explicitly.
Summary table
| Call | Candidates | Phase that matches | Chosen |
|---|---|---|---|
| `show(5)` with `long`, `Integer`, `Object` | `long` | 1 (widening) | `show(long)` |
| `print(1)` with `int...`, `Integer` | `Integer` | 2 (boxing) | `print(Integer)` |
| `print(1, 2)` with `int...`, `Integer` | `int...` | 3 (varargs) | `print(int...)` |
| `takesLong(5)` with `Long` | none | none | compile error |
| `g(1, 2)` with two mixed boxing overloads | both | 2 | ambiguous |
Exercise
Given static void m(long x), static void m(Integer x) and static void m(int... x), which method does each of these calls reach: m(3), m(Integer.valueOf(3)), and m(3, 4)? Explain using the phases.
Show answer
m(3) reaches m(long). In phase 1, int widens to long with no boxing, and the search stops there. m(Integer.valueOf(3)) reaches m(Integer). In phase 1 it matches by identity, and m(long) does not apply because unboxing is not allowed in phase 1. m(3, 4) reaches m(int...). No fixed-arity method takes two arguments, so phases 1 and 2 find nothing, and phase 3 allows variable arity.
Exercise
Why does static void f(Long x) {} called as f(5) fail to compile, while Long y = 5L; and static void f(long x) {} called as f(5) both work?
Show answer
An int can box only to Integer, and Java does not allow primitive widening followed by boxing, so int cannot become Long in a method call. 5L is already a long, which boxes to Long. For f(long), the int argument widens to long in phase 1. The fix for f(Long) is to pass 5L or cast with (long) 5.