Parameter Matching Rules
Exact Type Matching
When calling a method, Java first attempts to find an exact type match:
public void processNumber(int value) {
System.out.println("Integer method: " + value);
}
// Exact match
processNumber(10); // Calls integer method
Widening Primitive Conversion
Java automatically promotes smaller primitive types to larger ones:
graph TD
A[byte] --> B[short]
A --> C[int]
B --> D[long]
C --> D
D --> E[float]
D --> F[double]
Widening Conversion Example
public void processNumber(long value) {
System.out.println("Long method: " + value);
}
processNumber(100); // int automatically converted to long
Autoboxing and Unboxing
Primitive Type |
Wrapper Class |
Autoboxing |
int |
Integer |
Automatic conversion |
double |
Double |
Automatic conversion |
boolean |
Boolean |
Automatic conversion |
public void processInteger(Integer value) {
System.out.println("Boxed integer: " + value);
}
processInteger(20); // Autoboxing from int to Integer
Method Overloading Resolution
Java follows a specific order when resolving method calls:
- Exact match
- Widening primitive conversion
- Autoboxing
- Varargs methods
public void display(int x) {
System.out.println("Integer method");
}
public void display(double x) {
System.out.println("Double method");
}
display(10); // Calls integer method
display(10.5); // Calls double method
Varargs Parameter Matching
public void processValues(int... values) {
for (int value : values) {
System.out.println(value);
}
}
processValues(1, 2, 3); // Variable number of arguments
processValues(); // Zero arguments also valid
Potential Ambiguity Scenarios
public void ambiguousMethod(Integer x) {
System.out.println("Integer method");
}
public void ambiguousMethod(int... x) {
System.out.println("Varargs method");
}
// Potential compilation error due to ambiguity
// ambiguousMethod(null);
LabEx Insight
At LabEx, we recommend understanding these matching rules to write more predictable and efficient Java methods.