Java 5: Varargs

  Java Features     Java 5     Java 7     Java 8  
Java 5 features
 Enhanced for Loop |   Varargs |   Static import |   Autoboxing and unboxing |   Enum types |   Generics |   Annotations |   By date 

Varargs allows you to avoid writing a method several times for multiple arguments. Before this feature, the solution was overloading methods. If the number of the arguments is unknown, you can use Varargs as shown in the exercise below. For more info click here to read Oracle’s explanation.

Note: By applying this feature to different types of arguments Varargs should be the last argument, see example 2.

Example 1: Varargs code

What is the output of the following code?

public class Varargs
{
  // varargs arguments
  void write(String...names)
  {
    System.out.print("Robin");
    for(String str: names)
    {
      System.out.print(str);
    }
    System.out.println(",");
  }
  public static void main(String[] args)
  {
    Varargs vg = new Varargs();
    // no-argument demo
    vg.write();
    // one-argument demo
    vg.write(" Emma");
    // two-argument demo
    vg.write(" David", " Vera");
    // four-argument demo
    vg.write(" Einstein", " Newton",
        " Darwin", " Tesla");
  }
}
Author: Sar Maroof

Answer explanation

By using Verargs invoking the methods with different arguments is possible.
Therefore, the program writes the following to the standard output.

Robin,
Robin Emma,
Robin David Emily Vera,
Robin Einstein Newton Darwin Tesla,

Example 2: Varargs as last argument

What is the output of the following code?

public class Varargs
{
  // int and varargs arguments
  void write(int age, String...names)
  {
    for(String str: names)
    {
      System.out.print("Name: " + str);
      System.out.println(", Age: " + age);
    }
  }
  public static void main(String[] args)
  {
    Varargs vg = new Varargs();
    // two-argument demo
    vg.write(23, "Emma");
    // three-argument demo
    vg.write(31, "David", "Vera");
  }
}
Author: Sar Maroof

Answer explanation

This code write the following to the standard output.
Name: Emma, Age: 23
Name: David, Age: 31
Name: Vera, Age: 31





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *