Varargs is a special syntax that allows a method to accept a variable (any) number of arguments of one type. In the method declaration, such a parameter is denoted as Type... name (for example, int... nums). Inside the method, the arguments are treated as a regular array.
Example:
public void printNumbers(int... nums) { for (int n : nums) { System.out.print(n + " "); } }
You can call it like this:
printNumbers(1, 2, 3, 4); // or printNumbers();
Internal implementation: When a method with varargs is called, the compiler automatically creates an array of the corresponding type.
Limitations and nuances:
printNumbers(null) will cause an NPE when attempting to iterate.Question: "Can you declare a method with multiple varargs parameters?"
Common mistake: Many believe that you can declare public void example(int... a, String... b), but this will cause a compilation error.
Correct answer: No, there can be only one varargs parameter, and it must be the last.
Story
In a corporate logging library, overloaded versions of methods with varargs and arrays were implemented. When passing an array instead of a set of elements, the wrong version of the method was applied, resulting in the array being logged as an object rather than its contents. This caused confusion when analyzing logs.
Story
In an integration service, a method call with varargs accepted null without checking for NPE. The system unexpectedly "crashed" when trying to iterate elements, as at least an empty array was expected.
Story
In one e-commerce project, there was confusion with method overloads: there was a method
send(String subject, String... emails)and another —send(String subject, String[] emails). When passing an array, the compiler implicitly chose the wrong method. The result: emails were not sent to clients.