ProgrammingBackend Java Developer

What are varargs (variable-length arguments) in Java, how does their internal implementation work, and what nuances and limitations exist when using them?

Pass interviews with Hintsage AI assistant

Answer

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:

  • There can be only one varargs parameter, and it must always be the last in the list of parameters.
  • The varargs expansion (Type...) is essentially an array (Type[]).
  • Passing null: printNumbers(null) will cause an NPE when attempting to iterate.
  • Overloading methods with varargs can lead to ambiguity in calls.

Trick question

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.

Examples of real errors due to ignorance of the topic nuances


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.