Java tutorial

Learn how to create Java methods with variable amount of arguments.

Creating methods with variable amount of arguments is a very simple concept named varargs (VARiable ARGumentS). All you have to do is to provide varargs type parameter as the very last parameter in your method. The varargs parameter type is defined by adding three dots after parameter type name.

Take a look at the example code below.

public class Prototyping {
   public static void main(String[] args) {
      greetPeople("Howdy", "Adam", "Peter", "Jeanne", "Bear", "Arnie");

   static void greetPeople(String greeting, String... names) {
      for(String name : names) {
         System.out.println(greeting+" "+name+"!");

The code above generates following output.

Howdy Adam!
Howdy Peter!
Howdy Jeanne!
Howdy Bear!
Howdy Arnie!

The purporse of our greetPeople() method is to greet unspecified amount of people with provided greeting. The first parameter of the method is String greeting which is the greeting that is going to be used. The second parameter is varargs parameter String… names (notice three dots after parameter type: String…) in which we will store names of people to greet.

As our varargs parameter is on the second place in the method, any argument that will be provided as second and later will be put into array that will be available under names variable in the method body.

Learn more about Java