Methods, Arrays & Strings

Variable Arguments (varargs)

15 min Lesson 4 of 14

Variable Arguments (varargs)

So far you have written methods where you know exactly how many parameters to declare. But what if the number of values a caller wants to pass in is not fixed? Java solves this elegantly with variable arguments, commonly called varargs. They let a single method accept any number of arguments of the same type — zero, one, or many — without requiring the caller to build an array first.

The ... Syntax

You declare a varargs parameter by placing three dots (...) between the type and the parameter name:

public static int sum(int... numbers) { int total = 0; for (int n : numbers) { total += n; } return total; }

Inside the method, numbers behaves exactly like a regular int[] array. The Java runtime automatically collects whatever arguments the caller passes and wraps them in that array for you.

Here is how a caller can use the method above:

System.out.println(sum()); // 0 — zero arguments is valid System.out.println(sum(5)); // 5 System.out.println(sum(1, 2, 3)); // 6 System.out.println(sum(10, 20, 30, 40)); // 100
Under the hood it is an array. When you write sum(1, 2, 3), the compiler silently turns it into sum(new int[]{1, 2, 3}). That means you can also pass a pre-built array directly: int[] vals = {4, 5, 6}; sum(vals);. Both styles compile and behave identically.

Why Use Varargs?

Consider the alternative without varargs. To allow flexible argument counts you would need multiple overloads or force every caller to create an array:

// Without varargs — tedious overloads public static int sum(int a) { return a; } public static int sum(int a, int b) { return a + b; } public static int sum(int a, int b, int c) { return a + b + c; } // What about four values? Five? It never ends.

Varargs replace all of those overloads with one clean method. You write the logic once, and callers get a natural syntax that reads like plain arguments.

Varargs with Other Parameters

A varargs parameter can be combined with normal parameters, but with one strict rule: the varargs parameter must always come last in the parameter list.

public static void printReport(String title, int... scores) { System.out.println("Report: " + title); int total = 0; for (int s : scores) { total += s; } System.out.println("Total score: " + total); }

Calling this method:

printReport("Math Test", 85, 90, 78); // Output: // Report: Math Test // Total score: 253 printReport("Empty Quiz"); // Output: // Report: Empty Quiz // Total score: 0

The first argument always binds to title. Everything after it — however many values — feeds into the scores array. If no score values are provided, scores is simply an empty array (length 0), not null.

Always check length, not null. Because the runtime guarantees the varargs parameter is a real (non-null) array, it is safe to iterate over it with a for-each loop even when the caller passes zero arguments. You never need a null check.

A Common Real-World Pattern: String Formatting Helpers

The Java standard library uses varargs heavily. String.format(), System.out.printf(), and many logging frameworks accept a format string followed by a varargs array of values:

// From the standard library — simplified signature public static String format(String format, Object... args) // In use String msg = String.format("Hello %s, you scored %d out of %d.", "Alice", 42, 50); System.out.println(msg); // Hello Alice, you scored 42 out of 50.

Understanding varargs helps you read and use such APIs confidently.

Limitations and Pitfalls

  • Only one varargs per method. You cannot write void foo(int... a, String... b) — the compiler rejects it.
  • Must be last. void foo(int... nums, String label) does not compile.
  • Overloading ambiguity. If you overload a method and one version uses varargs, the compiler may not know which version to call. Keep overloads unambiguous.
Varargs and generics do not mix cleanly. Writing T... items generates a compiler warning about "heap pollution". For now, be aware the warning exists; it can be suppressed with @SafeVarargs on final or static methods. You will learn about generics later in the course.

Summary

Varargs (type... name) let you write a single method that accepts any number of arguments of the same type. Inside the method, the parameter is treated as an ordinary array. The varargs parameter must always appear last in the signature. Use varargs when the number of inputs is genuinely variable, but prefer regular parameters when the count is fixed — that makes the API clearer and avoids accidental misuse.