Question

Java Varargs Explained: What `String...` Means in Method Parameters

javavariadic-functions

Question

In Java, what do the three dots after String mean in a method parameter like this?

public void myMethod(String... strings) {
    // method body
}

I want to understand what String... strings does, how the method can be called, and how it differs from using a normal array parameter.

Short Answer

By the end of this page, you will understand that String... strings in Java is called varargs (variable-length arguments). You will learn how Java lets a method accept zero or more values of the same type, how varargs are treated like arrays inside the method, when to use them, and the common mistakes beginners make when working with them.

Concept

In Java, the syntax Type... name means the method accepts a variable number of arguments of that type. This feature is called varargs.

So this method:

public void myMethod(String... strings) {
    // method body
}

means:

  • myMethod can be called with zero, one, or many String values
  • Inside the method, strings behaves like a String[] array

For example:

myMethod();
myMethod("apple");
myMethod("apple", "banana", "orange");

Java collects those arguments into an array automatically.

This is useful because it makes method calls cleaner and more flexible. Without varargs, you would often need to create an array manually before calling the method.

Varargs matter in real programming because many APIs need to accept an unknown number of values. Common examples include:

  • logging methods
  • utility methods
  • formatting methods like String.format()
  • methods that combine or validate many inputs

Important rule: a method can have only one varargs parameter, and it must be the last parameter in the method signature.

Mental Model

Think of varargs like a shopping basket at a store checkout.

  • A normal parameter is like handing over exactly one item.
  • A varargs parameter is like handing over any number of similar items in one basket.

For String... strings:

  • each String is one item
  • Java puts all of them into a basket
  • inside the method, that basket is just an array

So even though the caller writes:

myMethod("a", "b", "c");

inside the method, Java is effectively working with something like:

String[] strings = {"a", "b", "c"};

The basket can also be empty:

myMethod();

In that case, Java gives the method an empty array.

Take Quiz

Syntax and Examples

The basic syntax is:

returnType methodName(Type... parameterName) {
    // use parameterName like an array
}

Example 1: Simple varargs method

public class Demo {
    public static void printWords(String... words) {
        for (String word : words) {
            System.out.println(word);
        }
    }

    public static void main(String[] args) {
        printWords();
        printWords("Java");
        printWords("Java", "Python", "C++");
    }
}

What this does

  • printWords() passes no strings
  • printWords("Java") passes one string
  • printWords("Java", "Python", "C++") passes three strings
  • Inside the method, words is treated like a String[]

Example 2: Varargs with another parameter

public class Demo {
    public static void greetAll(String greeting, String... names) {
        for (String name : names) {
            System.out.println(greeting + ", " + name);
        }
    }

    public static void main(String[] args) {
        greetAll("Hello", "Ava", "Ben", "Chris");
    }
}

This works because the varargs parameter is last.

Example 3: Equivalent array form

Varargs are very similar to arrays.

public void myMethod(String... strings) {
    System.out.println(strings.length);
}

is used almost like:

public void myMethod(String[] strings) {
    System.out.println(strings.length);
}

The main difference is in how the method is called. With varargs, Java lets you pass values directly instead of manually building an array every time.

myMethod("x", "y", "z");

Instead of:

myMethod(new String[]{"x", "y", "z"});

Step by Step Execution

Consider this example:

public class Demo {
    public static void showCount(String... items) {
        System.out.println("Count: " + items.length);

        for (String item : items) {
            System.out.println(item);
        }
    }

    public static void main(String[] args) {
        showCount("red", "green", "blue");
    }
}

Step-by-step

  1. The main method calls:

    showCount("red", "green", "blue");
    
  2. Because showCount uses String... items, Java collects the arguments into an array.

    Conceptually, this is like:

    String[] items = {"red", "green", "blue"};
    
  3. Inside showCount, items.length is 3, so this prints:

    Count: 3
    
  4. The enhanced for loop goes through each array element:

    • first: red
    • second: green
    • third: blue
  5. The full output is:

Count: 3
red
green
blue

What if no arguments are passed?

showCount();

Then items is an empty array:

  • items.length is 0
  • the loop runs zero times

That is why varargs are convenient for optional multiple values.

Real World Use Cases

Varargs are useful when a method should accept any number of values of the same type.

1. Logging messages

log("START", "User signed in", "id=42");

A logging helper can accept multiple details without forcing the caller to build an array manually.

2. Utility methods

int total = sum(10, 20, 30, 40);

A math or helper method can process many numbers.

3. Building SQL placeholders or query parts

selectColumns("id", "name", "email");

A utility method can accept a flexible list of column names.

4. Validation methods

requireNonEmpty(name, email, password);

A method can check many fields in one call.

5. Test helpers

assertContainsAll(list, "A", "B", "C");

In tests, varargs make helper methods easy to read and convenient to use.

Take Quiz

Real Codebase Usage

In real Java projects, developers often use varargs for convenience APIs.

Common patterns

  • Helper methods that accept many values
  • Wrapper methods around arrays or collections
  • Validation methods that check multiple inputs
  • Formatting and logging methods

Example: Guard clause with varargs

public static void requireNonNull(Object... values) {
    for (Object value : values) {
        if (value == null) {
            throw new IllegalArgumentException("Value cannot be null");
        }
    }
}

This lets you write:

requireNonNull(name, email, password);

Example: Convert varargs to a list

public static List<String> toList(String... values) {
    return Arrays.asList(values);
}

Example: Early return pattern

public static void printIfAny(String... messages) {
    if (messages.length == 0) {
        return;
    }

    for (String message : messages) {
        System.out.println(message);
    }
}

Important design note

Varargs are best when:

  • the number of arguments can vary
  • all extra values are the same type
  • the method should be easy to call

If the data is already in a List or another collection, passing a collection may be clearer than converting everything to varargs.

Common Mistakes

1. Thinking varargs are a completely different type

Inside the method, varargs are just an array.

public void myMethod(String... strings) {
    System.out.println(strings.length); // valid
}

2. Putting the varargs parameter anywhere except last

This is invalid:

public void badMethod(String... names, int count) {
    // error
}

Why it fails:

  • Java would not know where the variable-length arguments end and the next parameter begins.

Correct version:

public void goodMethod(int count, String... names) {
    // valid
}

3. Using more than one varargs parameter

This is invalid:

public void badMethod(String... a, int... b) {
    // error
}

A method can only have one varargs parameter.

4. Forgetting that zero arguments are allowed

public static void printAll(String... values) {
    System.out.println(values.length);
}

This is valid:

printAll();

So do not assume the array has at least one item.

5. Confusing varargs with null

You can call a varargs method with null, but this can be confusing.

printAll((String[]) null);

Now the parameter itself is null, not an empty array.

That means this can crash:

public static void printAll(String... values) {
    System.out.println(values.length); // NullPointerException if values is null
}

Safer version:

public static void printAll(String... values) {
    if (values == null) {
        return;
    }

    for (String value : values) {
        System.out.println(value);
    }
}

6. Overusing varargs

Varargs are convenient, but not always the best design.

If your method really expects a collection of data that is already stored in a List, using List<String> may be clearer and more flexible.

Comparisons

ConceptSyntaxHow caller uses itInside methodBest for
Normal parameterString namePass exactly one valueSingle StringOne required value
Array parameterString[] namesUsually pass an arrayString[]When caller already has an array
Varargs parameterString... namesPass zero or more values directlyString[]Flexible method calls

Varargs vs array parameter

public void withArray(String[] names) {}
public void withVarargs(String... names) {}

Both receive an array internally, but varargs are easier to call:

withArray(new String[]{"A", "B"});
withVarargs("A", "B");

Varargs vs List<String>

OptionGood whenLimitation
String...You want convenient method callsOnly works naturally for same-type arguments
List<String>Data already exists as a collectionSlightly more verbose to call

Varargs vs method overloading

Without varargs, you might write many overloads:

void print() {}
void print(String a) {}
void print(String a, String b) {}
void print(String a, String b, String c) {}

With varargs:

void print(String... values) {}

Varargs reduce repetition when the only difference is the number of same-type parameters.

Take Quiz

Cheat Sheet

Java varargs quick reference

  • Syntax:
void methodName(Type... values) {}
  • Example:
void printNames(String... names) {}
  • Call forms:
printNames();
printNames("Ana");
printNames("Ana", "Ben", "Cara");
printNames(new String[]{"Ana", "Ben"});
  • Inside the method, varargs act like an array:
names.length
names[0]
for (String name : names) {}

Rules

  • Only one varargs parameter per method
  • Varargs parameter must be last
  • Varargs can accept zero or more arguments
  • Inside the method, the varargs parameter is an array

Common pattern

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

Edge case

Be careful with null:

sum();            // empty array
printAll((String[]) null); // actual null reference

Memory shortcut

Type... means: "accept many values, but treat them as an array inside."

FAQ

What is String... called in Java?

It is called varargs, short for variable-length arguments.

Is String... strings the same as String[] strings?

Inside the method, yes: it behaves like an array. The main difference is that varargs make the method easier to call.

Can a varargs method be called with no arguments?

Yes. Java passes an empty array when no values are provided.

Can I have more than one varargs parameter in a method?

No. A method can only have one varargs parameter.

Why must the varargs parameter be last?

Because Java needs to know which arguments belong to the variable-length part of the call.

Can I pass an array to a varargs method?

Yes. You can pass a normal array directly.

String[] names = {"A", "B"};
myMethod(names);

When should I use varargs instead of a list?

Use varargs when you want convenient method calls with a flexible number of same-type values. Use a List when the data already exists as a collection or when collection operations are needed.

Take Quiz

Mini Project

Description

Create a small Java utility that prints tags passed into a method. This project demonstrates how varargs let you accept a flexible number of String values and process them like an array. It is practical because many real programs need helper methods that accept any number of values, such as labels, categories, or messages.

Goal

Build a method that accepts zero or more tags and prints how many were provided, then prints each tag on its own line.

Requirements

  • Create a method that uses String... as a parameter.
  • Print the total number of tags received.
  • Loop through the tags and print each one.
  • Call the method with zero, one, and multiple tags.
  • Keep the program runnable from a main method.
Take Quiz

Keep learning

Related questions

View more