0Pricing
Java Academy · Lesson

Varargs Parameters

Define methods that accept variable-length argument lists and combine them with arrays.

Varargs Parameters is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Varargs Parameters

Varargs (variable-length argument lists) let you define methods that accept any number of arguments of the same type, internally treated as an array.

Declaring Varargs

Use Type... name for a varargs parameter. It must be the last parameter and there can only be one per method.

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

System.out.println(sum());           // 0 (empty array)
System.out.println(sum(1));          // 1
System.out.println(sum(1, 2, 3));    // 6
System.out.println(sum(1, 2, 3, 4)); // 10

// Can also pass an array
int[] arr = {5, 10, 15};
System.out.println(sum(arr));        // 30

Varargs Internally

Varargs are syntactic sugar. The compiler turns the call into an array creation at the call site.

// Calling: sum(1, 2, 3)
// Compiler generates: sum(new int[]{1, 2, 3})

static void printAll(String label, String... items) {
    System.out.println(label + ":");
    for (String item : items) System.out.println("  - " + item);
}

printAll("Fruits", "Apple", "Banana", "Cherry");
// Fruits:
//   - Apple
//   - Banana
//   - Cherry

printAll("Empty"); // varargs is empty array

Mixed Parameters with Varargs

Varargs must be the last parameter. You can mix normal parameters before it.

static double average(String label, double... values) {
    if (values.length == 0) return 0.0;
    double sum = 0;
    for (double v : values) sum += v;
    double avg = sum / values.length;
    System.out.printf("%s average: %.2f%n", label, avg);
    return avg;
}

average("Math scores", 92.0, 85.5, 78.0, 95.0);
// Math scores average: 87.62

average("Single value", 100.0);
// Single value average: 100.00

Varargs with Generic Types

Using varargs with generics causes a heap pollution warning. Suppress with @SafeVarargs when the method is provably safe.

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

@SafeVarargs  // suppresses heap pollution warning
static <T> List<T> listOf(T... elements) {
    return Arrays.asList(elements); // safe: we don't store to the array
}

List<String> names = listOf("Alice", "Bob", "Charlie");
System.out.println(names); // [Alice, Bob, Charlie]

List<Integer> scores = listOf(95, 87, 73);
System.out.println(scores); // [95, 87, 73]

Varargs and Overloading

When a varargs method is overloaded with an exact match, the exact match is preferred. Varargs are the last resort.

static void log(String msg)         { System.out.println("1-arg: " + msg); }
static void log(String m1, String m2) { System.out.println("2-arg: " + m1 + ", " + m2); }
static void log(String... msgs)        { System.out.println("varargs: " + msgs.length); }

log("hello");          // 1-arg: hello
log("a", "b");         // 2-arg: a, b
log("a", "b", "c");   // varargs: 3
log();                  // varargs: 0

printf is Varargs

System.out.printf uses varargs — it accepts a format string and any number of arguments of any type.

// printf signature: printf(String format, Object... args)
System.out.printf("%s ordered %d items for $%.2f%n",
    "Alice", 3, 59.97);
// Alice ordered 3 items for $59.97

// String.format is also varargs
String msg = String.format("Error %d: %s", 404, "Not Found");
System.out.println(msg); // Error 404: Not Found

Building a Logger with Varargs

Implementing a simple structured logger that accepts key-value pairs using varargs.

static void logEvent(String event, Object... keyValues) {
    if (keyValues.length % 2 != 0)
        throw new IllegalArgumentException("Key-value pairs required");
    StringBuilder sb = new StringBuilder(event);
    for (int i = 0; i < keyValues.length; i += 2)
        sb.append(" ").append(keyValues[i]).append("=").append(keyValues[i+1]);
    System.out.println(sb);
}

logEvent("user.login",  "userId", 42, "ip", "192.168.1.1", "success", true);
// user.login userId=42 ip=192.168.1.1 success=true

Performance Consideration

Each varargs call creates a new array on the heap. For high-frequency utility methods, provide fixed-arity overloads to avoid allocation.

// Java's own EnumSet does this:
static <E extends Enum<E>> EnumSet<E> of(E e)              { ... }
static <E extends Enum<E>> EnumSet<E> of(E e1, E e2)       { ... }
static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) { ... }
static <E extends Enum<E>> EnumSet<E> of(E e1, E... rest)  { ... }
// Avoids array creation for 1-3 args (most common case)

// Apply the same pattern to your own hot-path APIs:
static void report(String msg)             { log(new String[]{msg}); }
static void report(String m1, String m2)   { log(new String[]{m1, m2}); }
static void report(String... msgs)         { log(msgs); }

Varargs and null

Passing null to a varargs method is ambiguous — Java may interpret it as a null array. Use explicit cast to avoid the warning.

static void printItems(String... items) {
    if (items == null) {
        System.out.println("null array passed");
        return;
    }
    for (String item : items)
        System.out.println(item != null ? item : "(null element)");
}

printItems((String[]) null); // null array passed
printItems(null, "valid");   // (null element), valid
printItems();                 // empty array (0 items)

Practical: String format Helper

A safe printf wrapper that returns the formatted string, using varargs to match the format-args style.

static String fmt(String pattern, Object... args) {
    try {
        return String.format(pattern, args);
    } catch (java.util.IllegalFormatException e) {
        return "[FORMAT ERROR: " + e.getMessage() + "]";
    }
}

System.out.println(fmt("User %s has %d orders", "Alice", 5));
// User Alice has 5 orders

System.out.println(fmt("Invalid %z format", "arg"));
// [FORMAT ERROR: Conversion = 'z' ...]

Quick Check

What is the type of a varargs parameter inside the method body?

Recap: Varargs Parameters

Key takeaways:

  • Varargs (Type... name) accepts 0 or more arguments internally as an array
  • Must be the last parameter — only one varargs parameter per method
  • Caller can pass individual values or an array
  • Use @SafeVarargs to suppress heap pollution warnings for generic varargs
  • Exact-match overloads are preferred over varargs overloads
  • Provide fixed-arity overloads for frequently called methods to avoid array allocation

Frequently asked questions

Is the “Varargs Parameters” lesson free?

Yes — the full text of “Varargs Parameters” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Varargs Parameters”?

Define methods that accept variable-length argument lists and combine them with arrays. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Varargs Parameters” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Method Overloading Rules
  2. Varargs Parameters
  3. Static Fields and Constants
  4. Utility Classes and Static Factory Methods
← Back to Java Academy