Varargs (variable-length arguments) in Java allow you to pass a variable number of arguments of a specified type to a method. When using object types with varargs, Java treats them as an array internally.
Syntax of Varargs with Object Types
public static void printObjects(Object... objects) {
for (Object obj : objects) {
System.out.println(obj);
}
}
Here, `Object... objects` means the method can take zero or more `Object` arguments.
How Varargs Work with Objects
When a method is called using varargs, Java implicitly wraps the arguments into an array. This allows you to pass:
- Multiple objects
- Different types of objects (since all objects extend
Object
)
- No objects at all (empty array)
Examples
- Passing Multiple Objects
public class VarargsExample {
public static void main(String[] args) {
printObjects("Hello", 42, 3.14, new int[]{1, 2, 3});
}
public static void printObjects(Object... objects) {
for (Object obj : objects) {
System.out.println(obj);
}
}
}
Output:
Hello
42
3.14
[I@1b6d3586
> The last output `[I@1b6d3586` represents an array (`int[]`), as arrays do not override `toString()`.
- Passing No Arguments
printObjects(); // Works fine, prints nothing
Since varargs allow zero arguments, the method executes without errors.
- Passing an Explicit Array
You can pass an explicit `Object[]` array:
Object[] objArray = {"Java", 100, true};
printObjects(objArray);
This works the same way as passing individual arguments.
Rules and Considerations
-
Internally Treated as an Array
The method signature Object... objects
is equivalent to Object[] objects
.
-
Mixing Varargs with Regular Parameters
If other parameters exist, the varargs must be the last parameter in the method signature:
public static void display(String message, Object... objects) { }
â
Valid: display("Info", 1, "text", 3.5);
â Invalid: public static void display(Object... objects, String message) {}
(Varargs must be last)
-
Varargs and Method Overloading Ambiguity
If a method has both a single-array parameter and a varargs parameter, Java might not distinguish them clearly:
public static void print(Object[] arr) { }
public static void print(Object... arr) { }
Here, calling `print(new Object[]{"Test"})` might be ambiguous.
Best Use Cases for Varargs with Objects
- Logging utilities:
log(Object... messages)
- Debugging methods:
debug(Object... values)
- Flexible APIs: Methods that accept any number of heterogeneous arguments
Conclusion
Varargs with `Object...` in Java provide a flexible way to handle a variable number of arguments of different types. However, be mindful of ambiguity and performance considerations when working with large arrays.