System.out.println accepts an int, a double, a String or any object, and String.format accepts any number of values. These conveniences come from two features: method overloading, where several methods share one name, and varargs, where one method accepts a variable number of arguments. This lesson shows how to write both and how Java decides which overloaded method to call.
In this lesson you will learn
- What makes two methods valid overloads
- Writing varargs methods with
Type... - The rules for varargs parameters
- How Java picks an overload: exact match, widening, boxing, varargs
- Ambiguous calls and how to avoid them
You should know methods, arrays and wrapper classes and autoboxing.
Overloading and Varargs
public class Main {
// Overloading: same name, different parameter lists
static int area(int side) { return side * side; }
static int area(int width, int height) { return width * height; }
static double area(double radius) { return Math.PI * radius * radius; }
// Varargs: any number of int arguments, received as an array
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
// A varargs parameter must come last
static String label(String prefix, String... parts) {
return prefix + ": " + String.join(", ", parts) + " (" + parts.length + " parts)";
}
public static void main(String[] args) {
System.out.println("Square 5 : " + area(5));
System.out.println("Rectangle 4x6 : " + area(4, 6));
System.out.printf("Circle r=2 : %.2f%n", area(2.0));
System.out.println("sum() = " + sum());
System.out.println("sum(7) = " + sum(7));
System.out.println("sum(1, 2, 3, 4) = " + sum(1, 2, 3, 4));
int[] marks = {80, 75, 90};
System.out.println("sum(array) = " + sum(marks));
System.out.println(label("Fruits", "mango", "jackfruit", "lychee"));
System.out.println(label("Empty"));
}
}
Output
Square 5 : 25
Rectangle 4x6 : 24
Circle r=2 : 12.57
sum() = 0
sum(7) = 7
sum(1, 2, 3, 4) = 10
sum(array) = 245
Fruits: mango, jackfruit, lychee (3 parts)
Empty: (0 parts)
- Overloads must differ in their parameter list: number, types or order of parameters. A different return type alone is not enough.
int... numberslets the caller pass zero, one or many ints. Inside the method,numbersis an ordinaryint[].- You can also pass an existing array, as
sum(marks)shows. - A method can have only one varargs parameter, and it must be the last one, as in
label(String prefix, String... parts).
How Java Chooses an Overload
public class Main {
static void show(int x) { System.out.println("int version: " + x); }
static void show(long x) { System.out.println("long version: " + x); }
static void show(double x) { System.out.println("double version: " + x); }
static void show(Integer x) { System.out.println("Integer version: " + x); }
static void show(int... x) { System.out.println("varargs version, " + x.length + " values"); }
static void print(Object o) { System.out.println("Object: " + o); }
static void print(String s) { System.out.println("String: " + s); }
public static void main(String[] args) {
byte b = 10;
show(5); // exact match
show(b); // byte widens to int
show(5L); // long
show(5.0f); // float widens to double
show(Integer.valueOf(5)); // exact Integer
show(1, 2); // only varargs fits
print("hello"); // String is more specific than Object
print(42); // int boxed to Integer, which is an Object
print((Object) "hello"); // the cast chooses the Object version
}
}
Output
int version: 5
int version: 10
long version: 5
double version: 5.0
Integer version: 5
varargs version, 2 values
String: hello
Object: 42
Object: hello
The compiler looks for a match in three phases and stops at the first phase that works:
- Exact match or widening of primitives:
byte→int,float→double. That is whyshow(b)calls theintversion. - Boxing or unboxing:
int↔Integer.print(42)boxes toInteger, which then matchesObject. - Varargs, only when nothing else fits:
show(1, 2).
Within a phase, the most specific method wins. String is more specific than Object, so print("hello") picks the String version. A cast changes the compile-time type: print((Object) "hello") calls the Object version even though the value is still a string.
Overload or override?
Overloading means the same name with different parameters, chosen at compile time. Overriding means a subclass replaces a method with the same parameters, chosen at run time from the object’s real class.
Common Mistakes
- Overloading by return type only.
int get()andString get()do not compile together. - Ambiguous calls. With
f(Integer x, int y)andf(int x, Integer y), the callf(1, 2)fails to compile. - Passing
nullto overloaded methods.print(null)works here (String is most specific), but with two unrelated types it becomes ambiguous. - Too many overloads. If the behaviour differs, give methods different names, such as
areaOfCircle.
Practice Exercises
Exercise 1. Write a varargs method max(int first, int... rest) that returns the largest value and cannot be called with no arguments.
Show answer
static int max(int first, int... rest) {
int best = first;
for (int x : rest) if (x > best) best = x;
return best;
}
// max(4, 9, 2) returns 9; max(7) returns 7; max() does not compile
Requiring one normal parameter before the varargs guarantees at least one value.
Exercise 2. Using the second program, which version does show('A') call, and what does it print?
Show answer
A char widens to int, so the int version runs and prints int version: 65, the character code of ‘A’.
Frequently Asked Questions
Can constructors be overloaded?
Yes, and it is very common. A class can offer several constructors with different parameters, and one constructor can call another with this(…) to avoid repeating code.
Is varargs slower than passing an array?
Slightly, because Java creates a new array on every call. For normal code the difference does not matter; very hot methods sometimes add fixed overloads for one, two and three arguments, as List.of does.
Summary
- Overloads share a name but differ in parameter list.
Type...accepts any number of arguments as an array; it must be last.- Java tries exact/widening, then boxing, then varargs, and picks the most specific match.
- Overloading is decided at compile time; overriding at run time.
