Tiger (Java 5.0) Variable method arguments

Leon van Tegelen 1
0 0
Read Time:1 Minute, 3 Second

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);
    }

About Post Author

Leon van Tegelen

Consultant at AMIS
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

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

Some 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 […]
%d bloggers like this: