AI Hints
Home›Java Tutorial›Recursion, Varargs, Practice: Temperature Converter
Java · Lesson 62 of 120

Varargs

Any number of arguments.

⏱ 2 min read▶ Video at 1:17:30🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

What if a method should accept any number of values, two, five, or none? Java has varargs, short for variable arguments.

  • Any number of values
  • Even none
  • Called varargs

Three dots

Three dots after the type means any number of ints. Inside the method, nums is a normal array. So we can call sum with nothing, one number, or five. Varargs must come last, after the normal parameters. Printf uses varargs too. Run it. Zero, four, fifteen. Two colour words. And tea and cake.

Main.javajava
public class Main {
    static int sum(int... nums) {
        int total = 0;
        for (int n : nums) total += n;
        return total;
    }

    static void tag(String label, String... words) {
        System.out.println(label + ": " + words.length + " words");
    }

    public static void main(String[] args) {
        System.out.println(sum());
        System.out.println(sum(4));
        System.out.println(sum(1, 2, 3, 4, 5));
        tag("colours", "red", "green");
        System.out.printf("%s and %s%n", "tea", "cake");
    }
}
Output
0
4
15
colours: 2 words
tea and cake

Varargs rules

Write the type, three dots, then the name. Inside, it's an array. Only one varargs parameter is allowed. And it must be the last one.

keyvalue
int... numsany number of ints
Insidean int[] array
Only oneper method
Positionlast

Summary

Three dots let a method take any number of arguments, which arrive as an array. Next, a practice temperature converter.

Key takeaways
  • Type... name
  • Arrives as an array
  • Must be last
Next up: Practice: Temperature Converter — put module seven together