Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 201 ยท Methods

Variable Arguments (Varargs)

Learn Java varargs - the Type... syntax, how arguments become an array, the rules, null and empty calls, overloading pitfalls, and how String.format and List.of use them.

Some methods make sense with any number of arguments. A max method should work for two numbers or ten. A logging method should take a message and however many values belong in it. String.format("%s scored %d", name, points) takes a format string and then as many values as the format needs.

Java supports this with variable arguments, or varargs: put ... after the type of the last parameter, and callers can pass zero, one or many values there. Behind the scenes, those values arrive in your method as an ordinary array. This lesson covers the syntax, the rules the compiler enforces, the surprises around null, arrays and overloading, and the varargs methods you already use every day.

Declaring and calling a varargs method

Write the parameter type, three dots, and a name. Inside the method, the parameter is an array:

Java A sum method that takes any number of ints

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.

Look at what each call does:

  • sum(1, 2, 3): the compiler creates new int[] { 1, 2, 3 } for you and passes it.
  • sum(): the compiler passes an empty array (numbers.length == 0), never null.
  • sum(already): an int[] matches int... directly, so the array is passed as it is.

So int... numbers and int[] numbers mean the same thing inside the method. The difference is only at the call site: the varargs version also accepts a plain list of values.

The spacing doesn't matter: int... numbers, int ...numbers and int ... numbers all compile. The first is the common style.

The rules

The compiler enforces three rules:

  1. Only one varargs parameter per method. void f(int... a, String... b) is an error: the compiler couldn't tell where one list ends.
  2. It must be the last parameter. void log(String... parts, int level) is an error. Put fixed parameters first.
  3. Fixed parameters come first and are required. log(String level, Object... values) needs at least the level.

Rule 3 gives you a handy trick for "at least one" arguments. A plain int... values accepts zero values, so a max method would have to fail at runtime when called with none. Make the first value a normal parameter and the compiler does the checking:

Java Requiring at least one argument

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.

report mixes two fixed parameters with a varargs tail of Object..., so any values can follow: an int is autoboxed to Integer, a String is already an object. That's exactly how String.format and formatted are declared.

Varargs you already use

Varargs are everywhere in the Java standard library. A few you'll meet often:

Method Declaration (simplified)
String.format, "...".formatted, System.out.printf format(String format, Object... args)
List.of, Set.of of(E... elements) (plus fixed-arity overloads for up to 10)
Arrays.asList asList(T... a)
String.join join(CharSequence delimiter, CharSequence... elements)
Path.of of(String first, String... more)
Math.max? No! Only two ints, which is why you might write your own
Java Standard library varargs in action

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.

List.of has separate overloads for 0 to 10 elements, and a varargs overload for more. The JDK does this because creating the hidden array costs a little time and memory on every call; for the very common short cases, the fixed overloads avoid it. Your own methods rarely need that optimization.

Passing an array, null, or nothing

Because the parameter is an array, a few cases deserve attention.

An existing array is passed as is. The method sees your array, not a copy, so if the method modifies elements, the caller's array changes. When the compiler builds the array from a list of values, nobody else holds it, so there is no such risk.

null becomes a null array. sum((int[]) null) passes null as the array itself, and numbers.length then throws NullPointerException. Callers rarely do this on purpose, but a defensive method can check for it.

An empty call is an empty array. You never need a null check for sum().

The trickiest case is Object.... An Object[] argument is spread into the varargs, but a String[] is too, because a String[] is an Object[]. Pass a null alone and it's taken as the whole array, not one element:

Java Arrays and null with Object...

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.

In the "as one" line, the single element is the String[] itself, so Arrays.toString prints the array's type code and hash ([Ljava.lang.String;@...). The casts tell the compiler what you mean. Without them, show("label", words) spreads the array and show("label", null) passes a null array, but both compile with the warning "non-varargs call of varargs method with inexact argument type for last parameter", which is javac asking you to add the cast. When in doubt, cast: (Object) x for "one element", (Object[]) x for "this is the array".

A related trap: a primitive array is not an Object[]. Arrays.asList(new int[] {1, 2, 3}) gives a list with one element, the int[] itself, because int[] is a single object. Use Integer[], or a stream (Arrays.stream(ints).boxed().toList()), when you want a list of numbers.

Varargs and overloading

When several overloads could match a call, Java picks a varargs method only as a last resort. The compiler tries, in order:

  1. Exact and widening matches without boxing or varargs.
  2. Matches that need boxing or unboxing.
  3. Matches that need varargs.

So a fixed-arity overload always beats a varargs one when both fit:

Java Which overload wins?

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.

describe(5L) picks describe(double): widening a long to a double happens in phase 1, before varargs are even considered. (A long can't be narrowed to int, so int... wouldn't match anyway.) The full resolution rules live in Method Overloading.

Two varargs overloads can make calls ambiguous. With both f(int... a) and f(Integer... a), the call f() fails to compile with "reference to f is ambiguous": both match an empty list equally well. Avoid overloading a method with two varargs versions.

Generic varargs and @SafeVarargs

With a generic varargs parameter such as T... items, the compiler has to create an array of a generic type, which Java can't do safely (arrays and generics don't mix well, see Type Erasure and Generic Limitations). It compiles, but you get a warning about "possible heap pollution":

Java
static <T> List<T> listOf(T... items) {   // warning: possible heap pollution
    return new ArrayList<>(Arrays.asList(items));
}

If your method only reads the array (doesn't store into it or let it escape), you can promise that by marking it @SafeVarargs. The annotation is only allowed on methods that can't be overridden: static, final and private methods, and constructors.

Java
@SafeVarargs
static <T> List<T> listOf(T... items) {
    return new ArrayList<>(Arrays.asList(items));
}

That's what the JDK does on List.of, Arrays.asList and friends. For now, remember that the warning exists and that @SafeVarargs silences it only when the promise is true.

When to use varargs

Varargs are best when:

  • callers usually pass a few literal values: max(a, b, c), List.of("x", "y");
  • the number of values naturally varies: format arguments, path parts, log values.

Prefer a List or array parameter when callers usually already have a collection, or when the method stores the values. And keep performance in mind: each call to a varargs method with loose values allocates a new array. That's cheap, but in a tight loop that runs millions of times it can show up in profiles.

A good API reads naturally at the call site. Ask yourself which looks better: tags("java", "web") or tags(List.of("java", "web")). If it's the first, varargs is the right choice.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does count() print for void count(String... s) { IO.println(s.length); }?

    Calling a varargs method with no arguments passes an empty array, so s.length is 0. It is never null in that case.
  2. 2. Which declaration compiles?

    A method can have only one varargs parameter, and it must be the last one. Fixed parameters come first.
  3. 3. Given overloads f(int a, int b) and f(int... a), which one does f(1, 2) call?

    Overload resolution tries fixed-arity matches (without boxing, then with boxing) before considering varargs, so the two-int overload wins.
  4. 4. What does Arrays.asList(new int[] {1, 2, 3}).size() return?

    An int[] is not an Object[], so the whole array becomes a single element of type int[]. Use Integer[] or a boxed stream to get three elements.
  5. 5. Inside int sum(int... numbers), what is the type of numbers?

    A varargs parameter is an ordinary array inside the method, so you can use length, indexes and for-each on it.

Summary

  • Type... name as the last parameter lets callers pass zero or more values; there can be only one.
  • Inside the method the parameter is a normal array; an empty call gives an empty array, not null.
  • An existing array of the right type is passed directly (not copied); (Object) and (Object[]) casts control how arrays and null are passed to Object....
  • Use a fixed first parameter (int first, int... rest) to require at least one value.
  • Overload resolution considers varargs last; avoid two varargs overloads of the same method.
  • String.format, printf, List.of, String.join and Path.of are varargs methods; generic varargs warn about heap pollution unless marked @SafeVarargs.

Next: The main Method and Command-Line Arguments, where you'll take apart public static void main(String[] args) and use the arguments a program receives.