Java

Java varargs and arrays


Although I had known about varargs (variable number of arguments) since Java 5, strangely I didn’t know that arrays can be given in place of varargs until yesterday (criminal I know :))

 package javaapplication2;
 public class JavaApplication2 {

    public void printAll(String... strs){
        for (String str: strs){
            System.out.println(str);
        }
    }
    
    public static void main(String[] args) {
        String[] strs = {"hello","world"};
        new JavaApplication2().printAll(strs); //String array param
        new JavaApplication2().printAll("hello","sri lanka"); //multiple string params
    }
}

And I also tried changing the parameter format of a class’s main method using varargs instead of the usual String[]. That seemed to work too..

public static void main(String... args) {
        System.out.println("args.length = " + args.length);
}

Varargs are convenient when programming. The official document gives a nice short introduction to them. The key points that I took from it was;

  1. The three periods after the final parameter’s type indicate that the final argument may be passed as an array or as a sequence of arguments.
  2. Varargs can be used only in the final argument position.
  3. As an API designer, you should use them sparingly, only when the benefit is truly compelling.
  4. Generally speaking, you should not overload a varargs method
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s