MyThinkPond

On Java, Python, Groovy, Grails, Spring, Node.js, Linux, Arduino, ARM, Embedded Devices & Web

  • Recent Posts

    March 2010
    M T W T F S S
    « Feb   Apr »
    1234567
    891011121314
    15161718192021
    22232425262728
    293031  
  • Subscribe Options

  • Awards

    JavaCodeGeeks
  • Most Valuable Blogger @ DZone
  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 175 other followers

  • Follow MyThinkPond on WordPress.com
  • Blog Stats

    • 366,804 hits
  • General Options

Commonly overlooked feature in Java 5 – varargs

Posted by Venkatt Guhesan on March 30, 2010

Today I’ll comment on a commonly overlooked feature now available in Java (since Java 5.0) called “varargs”.

How many times have you done this?


public ConstructorOne(String personFullName){
// Does something
}

//and later on added another constructor that took another parameter

public ConstructorOne(String personFirstName, String personLastName){
// Now breaks down the name to pass along two strings instead of one.
}

// and so on...

Well, not anymore. You now have a new arsenal in your toolkit. In comes, “varargs” – stands for variable arguments.

You can rewrite that as this.


public constructorOne(String... parts){
if (parts.length == 2){
//process personFirstName, personLastName here
} else{

//process personFullName logic hereĀ  }

}

Although this functionality exists in Scala (called Tuples) and does a better job – even while returning data of multiple types. This is a good start for Java.

Now the next question one would ask is – what happens when you want to pass a list of arguments of different types. Well here’s the solution:


public constructorOne(Object... parts){

//your logic here

}

Cheers.

Advertisements

One Response to “Commonly overlooked feature in Java 5 – varargs”

  1. Hey! I know this is kind of off topic but I was wondering if you knew where I could locate a captcha plugin
    for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding
    one? Thanks a lot!

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

 
%d bloggers like this: