Tiger (Java 5.0) Variable method arguments

Leon van Tegelen 1

In Java code you have to use arrays a lot if you want to pass a variable number of arguments to a method. The main method is an excellent and prominent example.

public static void man(String[] args) {

}

Java 5.o introduces a new notation ( type … name ) which in my opinion is very elegant and readable. See the following program for example.


public class VarArgs {

    public static void main(String ... args) {   :-)
        printUs("ONE","TWO","THREE");
        printUs("FOUR","FIVE");
    }

    private static void printUs(String ... args) {
       System.out.println("Var args method");
       for (int i = 0;i<args.length;i++) {
           System.out.println( args[i] );
       }
    }

    private static void printUs(String arg1,String arg2)  {
       System.out.println("Specific two argument method ");
       System.out.println( arg1 );
       System.out.println( arg2 );
    }
}

It produces the following output

Var args method
ONE
TWO
THREE
Specific two argument method
FOUR
FIVE

How about that for a main!

The args parameter is handled just like an array.
You can see if there is method specifying an explicit number of parameters of the requested type, it takes precedence

Of course you could also use the new for loop


 private static void printUs(String ... args) {
       System.out.println("Var args method");
       for (String s: args) System.out.println(s);
    }

One thought on “Tiger (Java 5.0) Variable method arguments

  1. How does that extend to other types? Do you have to use Object… for non-homogenic varargs? (first thing that comes to mind is printf like format)? Do integral types have to be wrapped?

Comments are closed.

Next Post

I18Nized Buttons with AccessKeys in Struts applications

Facebook0TwitterLinkedinSome time ago I wrote a post on HTML Buttons which are accessable using keyboard shortcuts. (alt-s for a save button for example). In the solution I proposed I used CSS to put background images on the buttons. One of the commenters noted that this approach gets quite tedious when […]