Java Varargs: Methods with a Variable Number of Arguments
Write Java methods that accept any number of arguments with varargs (Type... args): how the compiler packs arguments into an array, passing arrays directly, rules and restrictions, overloading with varargs, the null ambiguity, @SafeVarargs and heap pollution, and performance tips.
kvi5hnuCode Sprout team member7 min readOn this page
You can write methods that accept a variable number of arguments. They're usually called varargs methods. You've used one since the beginning of this course: printf. The calls
System.out.printf("%d", n);
System.out.printf("%d %s", n, "widgets");
both call the same method, although one passes two arguments and the other three.
How Varargs Work
printf is declared in PrintStream like this:
public class PrintStream {
public PrintStream printf(String fmt, Object... args) {
return format(fmt, args);
}
}
The ellipsis ... is part of the Java syntax. It says that the method can receive any number of objects in addition to the fmt parameter.
The method actually receives two parameters: the format string and an Object[] array holding all the other arguments. (Primitive arguments such as integers are autoboxed into objects; see the wrapper classes article.) printf then has the unenviable task of scanning the format string and matching the ith format specifier with args[i].
In other words, for the implementor of printf, Object... is exactly the same as Object[].
The compiler transforms each call, bundling the arguments into an array and autoboxing as needed:
System.out.printf("%d %s", new Object[] { Integer.valueOf(n), "widgets" });
![The call total(4.5, 12.25, 3) is compiled into total(new double[] {4.5, 12.25, 3.0}), and inside the method prices is a double array of length 3; printf calls similarly bundle autoboxed arguments into an Object array](https://code-sprout-content.laxmi.solutions/asset/2026/11/p7pw5qw6sf6cj6ih.png)
Defining Your Own Varargs Methods
You can define varargs methods with any element type, including primitives. Here's a method that adds up any number of prices:
public static double total(double... prices) {
double sum = 0;
for (double p : prices) sum += p;
return sum;
}
Call it like this:
double bill = total(4.5, 12.25, 3);
The compiler passes new double[] { 4.5, 12.25, 3 } to total. Inside the method, prices is an ordinary double[]: you can use prices.length, index it, and loop over it.
Calling total() with no arguments is legal too. prices is then an empty array (never null), and this total returns 0.0. If at least one argument is required, make it a separate parameter:
static int sumAll(int first, int... rest) { // sumAll() won't compile
int sum = first;
for (int r : rest) sum += r;
return sum;
}
Passing an array directly
It's legal to pass an array in place of the variable arguments:
System.out.printf("%d %s", new Object[] { Integer.valueOf(1), "widgets" });
double bill = total(new double[] { 1, 2, 3 });
That means you can change an existing method whose last parameter is an array into a varargs method without breaking any existing code. MessageFormat.format was enhanced this way in Java 5. You can even declare main as
public static void main(String... args)
Rules and Restrictions
- A method can have only one varargs parameter, and it must be the last parameter.
void f(int... a, String s)giveserror: varargs parameter must be the last parameter. Type... namedeclares a parameter of typeType[]. You can't overload one method withf(int[] a)and another withf(int... a): they have the same signature.- Varargs and arrays aren't fully interchangeable from the caller's side: a method declared
f(int[] a)can't be called asf(1, 2, 3).
Overloading with varargs
When resolving overloads, the compiler tries fixed-arity methods first and considers varargs methods only in the last phase (see overloading resolution). Given
static String pick(int a, int b) { return "pick(int, int)"; }
static String pick(int... values) { return "pick(int...)"; }
pick(1, 2) calls pick(int, int) and pick(1, 2, 3) calls pick(int...). Libraries use this to avoid the cost of creating an array for common cases: List.of has fixed overloads for 0 to 10 elements plus a varargs version for more, and EnumSet.of does the same. (Map.of stops at 10 fixed key/value pairs; for more, use the varargs Map.ofEntries(Map.entry(k, v), ...).)
The null ambiguity
What does g(null) mean for static void g(String... s): one null string, or a null array? The compiler treats null as the array (s == null inside the method) and warns:
warning: non-varargs call of varargs method with inexact argument type for last parameter;
cast to String[] for a non-varargs call and to suppress this warning
Say what you mean: g((String[]) null) passes a null array, and g((String) null) passes an array containing one null element. Inside a varargs method, it's reasonable to treat a null array as a programming error (Objects.requireNonNull(values)).
Generic Varargs and @SafeVarargs
Generics and varargs don't mix perfectly. Java can't create arrays of generic types like T[] safely (see the generics part), so a method such as
static <T> List<T> listOf(T... items) { return List.of(items); }
gets a warning: [unchecked] Possible heap pollution from parameterized vararg type T. Heap pollution means a variable of a parameterized type may end up referring to an object of the wrong type.
If the method only reads the array and doesn't store into it or leak it, it's safe. Tell the compiler so with @SafeVarargs, allowed on static, final and private methods and on constructors:
@SafeVarargs
static <T> List<T> listOf(T... items) {
return List.of(items);
}
JDK methods such as List.of(E...), Arrays.asList(T...) and Stream.of(T...) are annotated this way.
Varargs in the Standard Library
You use varargs methods all the time:
| Method | Example |
|---|---|
String.format, printf, formatted | "%s=%d".formatted(key, value) |
String.join(delimiter, elements...) | String.join("-", "x", "y", "z") → x-y-z |
List.of, Set.of, Stream.of | List.of("a", "b", "c") |
Arrays.asList | Arrays.asList(1, 2, 3) |
Objects.hash | Objects.hash(name, salary, startDate) |
MessageFormat.format | MessageFormat.format("{0} has {1} items", "Cart", 3) |
Path.of(first, more...) | Path.of("home", "user", "notes.txt") |
Everything Together
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public static double total(double... prices) {
double sum = 0;
for (double p : prices) sum += p;
return sum;
}
static String describe(String label, int... numbers) {
return label + ": " + numbers.length + " " + Arrays.toString(numbers);
}
static String pick(int a, int b) { return "pick(int, int)"; }
static String pick(int... values) { return "pick(int...)"; }
static int sumAll(int first, int... rest) { // at least one argument required
int sum = first;
for (int r : rest) sum += r;
return sum;
}
@SafeVarargs
static <T> List<T> listOf(T... items) { // only reads the array, so it is safe
List<T> result = new ArrayList<>(items.length);
for (T item : items) result.add(item);
return List.copyOf(result);
}
public static void main(String... args) {
System.out.println(total(4.5, 12.25, 3));
System.out.println(total()); // empty array
System.out.println(total(new double[] {1, 2, 3})); // pass an array directly
System.out.println(describe("none"));
System.out.println(describe("three", 1, 2, 3));
System.out.println(pick(1, 2)); // fixed arity wins
System.out.println(pick(1, 2, 3));
System.out.println(sumAll(5) + " " + sumAll(5, 6, 7));
System.out.printf("%d %s%n", new Object[] {42, "widgets"});
System.out.println(MessageFormat.format("{0} has {1} items", "Cart", 3));
System.out.println(listOf("a", "b", "c"));
System.out.println(String.join("-", "x", "y", "z"));
System.out.println(Arrays.asList(1, 2, 3));
}
}
19.75
0.0
6.0
none: 0 []
three: 3 [1, 2, 3]
pick(int, int)
pick(int...)
5 18
42 widgets
Cart has 3 items
[a, b, c]
x-y-z
[1, 2, 3]
Common questions
Is String... args in main any different from String[] args?
No. They compile to the same method signature, and the launcher calls both in the same way. The varargs form only matters when you call main from your own code with separate arguments.
Can a varargs parameter be primitive?
Yes. int... values gives you an int[] with no boxing. Mixing primitives and objects (Object... args) boxes every primitive argument, as printf does.
Why does Arrays.asList(intArray) give a list of one element?
asList(T... a) needs an object type for T. An int[] isn't a T[], so the whole array becomes a single element and you get a List<int[]>. Use Arrays.stream(intArray).boxed().toList(), or declare the array as Integer[].
When do I need @SafeVarargs?
When you write a method with a generic varargs parameter (T..., List<String>...) and you have checked that it doesn't store into the array or let it escape. Then the annotation removes the "possible heap pollution" warning for both you and every caller. It's allowed on static, final and private methods and on constructors.
Should my API take varargs or a List?
Varargs are convenient for a few literal values written at the call site (of(a, b, c)). Accept a Collection or List when callers usually already have their data in a collection. Many APIs offer both forms.
Summary
Type... namelets a method accept zero or more arguments ofType. Inside the method,nameis aType[]array (empty when no arguments are passed).- The compiler packs the arguments into a new array, autoboxing primitives for
Object.... - Callers may pass an array directly, so changing a trailing array parameter to varargs is backward compatible.
main(String... args)works. - Only one varargs parameter, and it must come last. Use a separate leading parameter to require at least one argument.
- Overload resolution prefers fixed-arity methods. Passing
nullalone is ambiguous; cast it. - Generic varargs produce heap-pollution warnings. Use
@SafeVarargswhen the method only reads the array.
Practice Questions
Write a varargs method average(int... values) that throws IllegalArgumentException when called with no values.
static double average(int... values) {
if (values.length == 0) throw new IllegalArgumentException("No values");
long sum = 0;
for (int v : values) sum += v;
return (double) sum / values.length;
}
Inside static void log(String... parts), what's parts when the call is log()? And log(null)?
For log(), parts is an empty array (length == 0). For log(null), parts is a null array, and the compiler warns. log((String) null) would give an array containing one null.
Is void f(String s, int... a) legal? Is void f(int... a, int... b)?
The first is legal: the varargs parameter is last. The second isn't: a method can have only one varargs parameter, and it must be last.
Given void print(Object o) and void print(Object... os), which one does print("hi") call?
print(Object). Fixed-arity methods are considered before varargs methods during overload resolution.
Why does List.of have overloads with 0 to 10 parameters if it already has a varargs version?
To avoid allocating an array on every call for the common small cases, and to let the implementation create compact specialized lists. The varargs overload covers larger lists.
Previous: Java Wrapper Classes and Autoboxing
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.