Java Reference ยท Keywords and Statements
Java varargs (variable arity methods)
Reference for Java varargs: declare methods with Type... parameters, how the compiler builds the array, overload rules, null pitfalls and @SafeVarargs.
A varargs parameter lets a method accept any number of arguments of the same type, including none. You declare it by writing three dots after the type: int... numbers. Inside the method, the parameter is a normal array (int[]), and the compiler packs the extra arguments into that array for you at each call.
String.format, Arrays.asList, List.of, and Path.of all use varargs.
static int sum(int... numbers) { int total = 0; for (int n : numbers) { total += n; } return total; } sum(); // 0 sum(1, 2, 3); // 6 sum(new int[] {4, 5}); // an array can be passed directly: 9
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
returnType name(Type... param) returnType name(FixedType a, FixedType b, Type... rest)
| Rule | Description |
|---|---|
| Position | The varargs parameter must be the last parameter, and a method can have only one. |
| Type | Inside the method it has type Type[]; param.length gives the count. |
| Calls | m(), m(a), m(a, b, c), or m(array) all work. |
| Constructors | Constructors can be varargs too. |
main |
public static void main(String... args) is the same as String[] args. |
Usage notes
- Overload resolution happens in three phases: first without boxing or varargs, then with boxing, then with varargs. Any applicable fixed-arity method wins over a varargs method, which is why
pick("a")printedsingle. - Ambiguity: overloads such as
f(int... a)andf(long... a)orf(String...)andf(Object...)can make a call likef()ambiguous or surprising. Avoid overloading varargs methods when possible. nullpitfalls:m(null)passes anullarray forObject...(the compiler warns), whilem(null, null)makes an array of two nulls. Cast to be explicit:(Object) nullor(Object[]) null.- Primitive arrays: an
int[]is not anObject[], soArrays.asList(intArray)yields aList<int[]>of size 1. UseArrays.stream(ints).boxed().toList()orIntStream. - Cost: each call allocates an array. This is fine for general code but visible in hot loops; JDK collections therefore provide fixed-arity overloads (
List.of(a),List.of(a, b), ...). - Generic varargs (
<T> void m(T... items)) create arrays of an erased type and produce an "unchecked generic array creation" warning.@SafeVarargssuppresses it on static, final, private, and constructor declarations, if the method does not store or expose the array. - Aliasing: if the caller passes an array, the method sees the same array, not a copy. Copy it (
values.clone()) if you keep it. - Design tip: when a method needs at least one argument, declare it as
m(T first, T... rest)instead of checkinglength == 0at run time.
Related
- Arrays,
Arrays.asList(),String.format(),List.of(), Generics syntax - Lessons: Varargs, Methods, Arrays