Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Interview Questions Java Java and Cryptography Interview Series Java Programming Java Tutorial Module 27 - Java Advanced and JVM Internals

Java Varargs Variable Length Arguments with Examples

Reviewed & accurate
AI Summary

Introduction

The java varargs feature shipped in Java 5 (September 2004) as part of JSR-176, the Tiger release, alongside generics, autoboxing, and the enhanced for-loop. It was designed by Gilad Bracha and the JSR-201 expert group to remove the boilerplate of explicitly constructing an array every time a method accepted a variable number of arguments. The Tiger syntax void log(String... args) was deliberately borrowed from C's varargs notation to make the migration path obvious for C and C++ developers moving to Java.

For a Java learner, java varargs is the cleanest way to design APIs that take a flexible number of inputs without forcing every caller to write new Object[]{a, b, c}. The feature powers System.out.printf, String.format, List.of, Set.of, Map.of, Arrays.asList, Stream.of, the reflection Method.invoke, the logging frameworks (SLF4J, Log4j2, java.util.logging), and almost every fluent builder in the JDK. Understanding varargs is essential because interviewers love to ask about the compile-time transformation from int... to int[], the precedence rules when more than one overload matches, and the heap pollution warning that arises when you combine varargs with generics.

What is Java Varargs?

Java varargs is a syntactic sugar feature that lets a method accept zero or more arguments of the same type, written as a formal parameter with three dots after the type, for example void log(String... messages). The three dots are an ellipsis token in the language grammar, not a typo -- the Java Language Specification section 8.4.1 formally calls this the variable arity parameter. Internally the JVM has no notion of varargs: at compile time the parameter is rewritten to an array, so log("a", "b", "c") becomes log(new String[]{"a", "b", "c"}).

Java varargs belongs to the language syntax category -- it is a compile-time translation, not a runtime feature. It is different from default arguments (Java does not have them) and from keyword arguments (Java does not have those either). The closest analogues are JavaScript's rest parameters function(...args), Python's *args, Kotlin's vararg, Scala's repeated-parameter *, and C# params. The crucial rules are: a method may declare at most one varargs parameter; the varargs parameter must be the last formal parameter; a varargs parameter of type T... is assignable from zero, one, or many comma-separated T values, from an explicit T[] array, and from nothing at all (zero arguments produces an empty array, never null).

How Java Varargs Works - Step by Step

Step 1: Source code. The developer writes a method with a variable arity parameter. For example, static int sum(int... nums). The compiler parses the three dots as the VariableArityParameter production of the JLS grammar and stores the parameter type as int[] in the class file's method descriptor. The compiler also generates a synthetic bridge flag if the method overrides a fixed-arity superclass method with the same name.

Step 2: Call site rewriting. When a caller writes sum(1, 2, 3), the compiler checks whether the runtime arguments can be assigned to the formal int[] parameter as an array literal. If yes, it rewrites the call to sum(new int[]{1, 2, 3}). If the caller passes zero arguments, the compiler emits sum(new int[0]) -- an empty array, never null. If the caller passes an existing int[] variable directly, no wrapping occurs; the array is passed by reference as-is, which is why modifying the array inside the method is visible to the caller.

Step 3: Overload resolution. If both sum(int a, int b) and sum(int... nums) exist, the compiler follows JLS 15.12.2: the most specific applicable method wins. Fixed-arity methods are preferred over variable-arity methods in phase 2 of overload resolution, so sum(1, 2) calls the two-argument version and sum(1, 2, 3) calls the varargs version. Calling sum() resolves to the varargs version because no fixed-arity method matches zero arguments.

Step 4: Heap pollution warning. If the varargs type is generic, for example static <T> List<T> of(T... items), the runtime array is always Object[] after erasure. This means a caller could later store a non-T reference into the array and trigger a ClassCastException at a remote read site -- a phenomenon called heap pollution (JLS 4.12.2). The compiler emits an unchecked warning unless the method is annotated @SafeVarargs (Java 7, JSR-334) which requires the method to be static, final, or a private constructor.

Step 5: Performance and ergonomics. Every varargs call allocates a fresh array, which is invisible to the JIT's escape analysis only when the array stays inside the called method body. The JDK adds overloads to skip the allocation in hot paths: List.of(), List.of(E), List.of(E, E), ... up to ten elements, and only then falls back to the varargs List.of(E...). This is why you should never micro-benchmark varargs inside a tight loop.

Java Program for Java Varargs

import java.util.Arrays;
import java.util.List;

public class VarargsDemo {

    // Varargs method: the compiler rewrites int... to int[]
    static int sum(int... nums) {
        int total = 0;
        for (int n : nums) {
            total += n;
        }
        return total;
    }

    // Mixed fixed + varargs: varargs must be last
    static String greet(String greeting, String... names) {
        if (names.length == 0) {
            return greeting + ", world!";
        }
        StringBuilder sb = new StringBuilder(greeting);
        for (int i = 0; i < names.length; i++) {
            sb.append(", ").append(names[i]);
        }
        return sb.toString();
    }

    // Overload: fixed arity beats varargs for two ints
    static int sum(int a, int b) {
        System.out.println("fixed 2-arg version");
        return a + b;
    }

    // Generic varargs - safe because we only read the array
    @SafeVarargs
    static <T> List<T> toList(T... items) {
        return Arrays.asList(items);
    }

    // Passing an explicit array skips the wrapping
    static int sumArray(int[] data) {
        int total = 0;
        for (int n : data) {
            total += n;
        }
        return total;
    }

    public static void main(String[] args) {
        // Zero arguments - empty array, not null
        System.out.println("sum()        = " + sum());
        // Five individual arguments
        System.out.println("sum(1..5)    = " + sum(1, 2, 3, 4, 5));
        // Two ints - fixed arity wins over varargs
        System.out.println("sum(2, 3)    = " + sum(2, 3));
        // Explicit array - no wrapping
        int[] data = {10, 20, 30};
        System.out.println("sumArray     = " + sumArray(data));
        // Mixed fixed + varargs
        System.out.println(greet("Hi"));
        System.out.println(greet("Hi", "Alice", "Bob"));
        // Generic varargs - @SafeVarargs suppresses the warning
        List<String> names = toList("Alice", "Bob", "Carol");
        System.out.println("names list   = " + names);
    }
}

Code Explanation - Line by Line

The sum(int... nums) method is the canonical varargs example: the formal parameter nums is internally typed as int[] by the compiler. Inside the method body, nums is treated exactly like a normal array -- the enhanced for-loop iterates over it, and the method returns the total. If the caller passes zero arguments, nums.length is 0 and the loop body is skipped, so the method returns 0. This empty-array behaviour is critical: a varargs parameter is never null unless the caller explicitly passes null.

The greet(String greeting, String... names) method demonstrates the rule that varargs must be the last formal parameter. The fixed greeting parameter is consumed first, and every subsequent argument becomes an element of names. The check if (names.length == 0) detects the zero-varargs case and falls back to a default world string, which is the same pattern the JDK uses inside String.join to return an empty string when there are no elements.

The overload sum(int a, int b) shows JLS 15.12.2 in action. When the compiler sees sum(2, 3), both the two-argument fixed-arity method and the one-argument variable-arity method are applicable. Phase 2 of overload resolution prefers fixed-arity methods, so the two-argument version is chosen. The output prints fixed 2-arg version to confirm the dispatch. When the compiler sees sum(1, 2, 3, 4, 5), only the varargs method is applicable, so the array {1, 2, 3, 4, 5} is constructed at the call site.

The generic method <T> toList(T... items) is annotated @SafeVarargs, which was added in Java 7. Without the annotation the compiler emits an unchecked warning for any generic varargs method, because type erasure means the runtime array is actually Object[] and heap pollution is possible. The annotation is the programmer's promise that the method body never stores a non-T reference into the array. The annotation can only be applied to static methods, final methods, or private constructors -- a non-final instance method could be overridden unsafely.

The sumArray(int[] data) method exists to highlight a subtle point: when a caller already has an array, it can pass it directly to a varargs method without any wrapping. The compiler skips the synthetic array allocation. This is also why a method that takes Object... can be called with a single Object[] argument and the JVM does not wrap it again, which historically confused developers migrating from Java 4 where they had to write new Object[]{new Object[]{...}}.

Interview Questions and Answers

Q1. What is the difference between an array parameter and a varargs parameter in Java?

A varargs parameter such as int... nums is pure syntactic sugar that the compiler rewrites to int[] nums in the class file's method descriptor. At runtime the JVM cannot distinguish a varargs method from any other array-taking method. The only differences are at the call site: a varargs caller may pass zero, one, or many comma-separated arguments (the compiler builds the array), while an array parameter caller must pass exactly one array reference. Both forms can be passed an explicit array variable.

Q2. Can a Java method declare more than one varargs parameter? Why or why not?

No. The Java Language Specification section 8.4.1 forbids more than one variable arity parameter per method and requires the varargs parameter to be the last formal parameter. The reason is call-site ambiguity: if two varargs parameters were allowed, the compiler could not decide where the first list ends and the second begins when reading comma-separated arguments. The same rule applies to lambda parameter lists and to record component lists.

Q3. What happens at the call site when you pass zero arguments to a varargs method?

The compiler synthesises an empty array of the component type and passes it. For void log(String... msgs), calling log() compiles to log(new String[0]). The array is never null, so the method body can safely iterate over it with an enhanced for-loop without a null check. This empty-array convention is also why String.join(",", "") returns an empty string and List.of() returns an immutable empty list.

Q4. Explain the @SafeVarargs annotation. When is it required and what restriction does it impose?

@SafeVarargs (Java 7, JSR-334) suppresses the unchecked heap-pollution warning the compiler emits for any generic varargs method. The annotation certifies that the method body never stores a non-T reference into the underlying array, so heap pollution cannot escape. The annotation can only be applied to static methods, final instance methods, or private constructors, because a non-final instance method could be overridden by a subclass that violates the contract. Without the annotation, the developer can suppress the warning with @SuppressWarnings("unchecked") but the API contract is weaker.

Q5. How does overload resolution choose between a fixed-arity method and a varargs method when both are applicable?

JLS 15.12.2 runs in three phases: phase 1 considers only fixed-arity methods with no boxing or varargs, phase 2 allows boxing and unboxing but still only fixed-arity methods, and phase 3 allows variable-arity methods. The first phase that finds an applicable method wins. So sum(2, 3) with both sum(int, int) and sum(int...) available resolves in phase 1 to the two-argument method, and only falls through to varargs in phase 3 if no fixed-arity method matches.

Q6. What is heap pollution, and how do generic varargs cause it?

Heap pollution (JLS 4.12.2) is when a variable of a parameterised type points to an object that is not of that type. With generic varargs like <T> void store(T... items), type erasure rewrites the array type to Object[] at runtime. If the method body or another caller stores a non-T reference into the array, a later read of the array through a generic-typed reference throws ClassCastException at a place that has nothing to do with where the wrong element was inserted. The @SafeVarargs annotation is the programmer's guarantee that no such pollution can escape the method.

Q7. Senior scenario: you are designing a high-throughput logging API that may be called millions of times per second. Should you expose varargs, and how would you avoid the array-allocation cost?

Varargs allocate a fresh array at every call site, which is invisible to the JIT's escape analysis only if the array stays inside the called method. For a hot logging path, the safer design is the one the JDK uses for List.of and Map.of: ship a dozen fixed-arity overloads that take 0, 1, 2, ... 10 arguments with no array allocation, and expose the varargs overload as a last resort for callers with more elements. Pair that with a Supplier<String>-style lambda overload so callers can defer the expensive message-building work until the logger has decided the level is enabled.

Sample Input and Output

Input: java VarargsDemo
Output:
sum()        = 0
sum(1..5)    = 15
fixed 2-arg version
sum(2, 3)    = 5
sumArray     = 60
Hi, world!
Hi, Alice, Bob
names list   = [Alice, Bob, Carol]

The output shows the five behaviours: the zero-argument call returns 0 because the array is empty, the five-argument call returns 15, the two-argument call dispatches to the fixed-arity overload (visible because the line fixed 2-arg version appears in the output), passing an explicit array avoids wrapping, and the generic varargs method returns an immutable Arrays.asList view containing the three names.

Common Mistakes to Avoid

First, passing null explicitly to a varargs method. Calling log(null) is ambiguous: the compiler cannot tell whether you meant zero arguments but with a null array reference, or one argument whose value is null. For an int... method, the call does not compile because null cannot be assigned to int. For a String... method, log(null) resolves to a one-element call where the single element is null, and then iterating throws NullPointerException. The fix is to call log() for zero arguments and log((String) null) for a single-null case.

Second, expecting the varargs array to always be a fresh defensive copy. The compiler-synthesised array is a new array, so mutating it inside the method is invisible to the caller. However, if the caller explicitly passes an existing int[], the method receives the same reference, and mutations are visible. Always document whether your varargs method reads or writes the array.

Third, applying @SafeVarargs to a non-final instance method. The compiler rejects the annotation on any method that could be overridden, because a subclass could break the no-heap-pollution contract. Make the method static, or make the class or method final, before applying the annotation.

Fourth, ignoring the heap-pollution warning on generic varargs. The warning means a ClassCastException may surface far from the source of the bug, often weeks later in production. If you cannot redesign the API to avoid generic varargs, at least audit the method body to confirm it never stores into the array, then apply @SafeVarargs with a comment.

Real-World Applications

The java varargs feature powers nearly every user-facing JDK API designed in the last twenty years. System.out.printf(String format, Object... args) has shipped varargs since Java 5 and replaces the older java.text.MessageFormat array-passing style. String.format, Formatter, and java.util.logging.Logger.log all follow the same pattern. The Java 9 immutable collection factories List.of(E...), Set.of(E...), and Map.of() use varargs as the catch-all overload on top of fixed-arity overloads to avoid the array allocation in the common cases.

Reflection depends on varargs: java.lang.reflect.Method.invoke(Object obj, Object... args) uses varargs to allow a caller to pass method arguments as a flat list. The compiler rewrites the call to an array, but if the underlying method itself takes an Object[] parameter, the caller must wrap it again to avoid the array being flattened incorrectly. Spring Framework uses varargs for BeanDefinitionReader.loadBeanDefinitions(String... locations) and similar resource-loading methods. SLF4J and Log4j2 expose logger.info(String format, Object... args) as the main entry point for parameterised logging. Test frameworks JUnit 5 and TestNG use varargs for parameterised test methods and the assertAll combinators.

Conclusion

Java varargs is a small piece of syntactic sugar with enormous ergonomic impact: it is the bridge between the array-typed JVM and the flat-argument style that humans prefer. We walked through the compile-time rewriting from T... to T[], the overload resolution phases that prefer fixed-arity methods, and the heap-pollution risk that @SafeVarargs controls. To go deeper, study the Java Language Specification sections 8.4.1 and 15.12.2, then read the List.of factory source in OpenJDK to see how the JDK skips the varargs allocation in hot paths. The natural follow-ups are the enhanced for-loop (which also goes through array iteration), the Object... reflection API, and Java 9 collection factories.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments