Method Overloading
Method Overloading in Java
Overloading lets you define multiple methods with the same name but different parameter lists in the same class. Java selects the correct version at compile time based on the argument types and count.
Rules for overloading
- Parameter lists must differ in number of parameters OR their types.
- Return type alone is NOT sufficient to distinguish overloads.
- Access modifiers may differ between overloads.
Varargs Variable-argument methods accept zero or more arguments of a type:
public static int sum(int... nums) { … }Internally, nums is an int[]. A varargs parameter must be the last parameter.
How Java picks the overload
- Exact match
- Widening conversion (e.g., int → long)
- Autoboxing (e.g., int → Integer)
- Varargs
Key points:
- Overloading improves API usability by providing convenient shortcuts.
- Don't overload to the point of confusion — parameter types should be meaningfully different.
Code Examples
public class Printer {
public static void print(int value) {
System.out.println("int: " + value);
}
public static void print(double value) {
System.out.println("double: " + value);
}
public static void print(String value) {
System.out.println("String: " + value);
}
public static void print(String label, int value) {
System.out.println(label + " = " + value);
}
public static void main(String[] args) {
print(42);
print(3.14);
print("hello");
print("score", 100);
}
}Java resolves the correct overload at compile time based on the argument types. The name is the same but the signatures differ.
public class Stats {
public static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
public static double average(double... nums) {
if (nums.length == 0) return 0;
double total = 0;
for (double n : nums) total += n;
return total / nums.length;
}
public static void main(String[] args) {
System.out.println(sum(1, 2, 3));
System.out.println(sum(10, 20, 30, 40));
System.out.println(average(4.0, 5.0, 6.0));
}
}Varargs (int...) lets callers pass any number of arguments. Internally it is an array, so you can iterate it with for-each.
Quick Quiz
1. Which of the following is a valid basis for method overloading?
2. Where must a varargs parameter appear in a method signature?
Was this lesson helpful?