Java Five-Oh #3: Variable Arguments

Variable arguments, or better known as varargs, where also introduced in Java 1.5. The neat thing about varargs is that you can construct a single method that will accept a varied number of arguments. When I am talking about varargs I an not talking about overloading, a single method will accept different number of parameters. Here is how you define a method that makes use of the new vararg feature:

public void print(String... args) {
   for(String s : args)
      out.println(s);
}

In the above sample code I declare vararg method by using the … notation in after the type in the parameter list. This method will accept zero or more string parameters. So the following method calls will be processed by the above function:

print("hello");
print("hello", "hola");

The thing to note is that the args parameter is just an array that is why I was able to use the for/in loop construct. I statically imported java.lang.System.out to make it available locally in the method implementation.

Enjoy. Share. Be Happy.
  • Twitter
  • Facebook
  • StumbleUpon
  • del.icio.us
  • Tumblr
  • Google Bookmarks
  • FriendFeed
  • Yahoo! Buzz
  • Reddit
  • Digg
  • HackerNews
  • Suggest to Techmeme via Twitter
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • Mixx
  • Furl

Related posts:

  1. Ruby Language Goodies For Java Developers
  2. Common Groovy Errors
  3. Java.class
  4. Java SE 6 Compiler API
  5. Generic Java

This entry was posted in Java, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*