Commonly overlooked feature in Java 5 - varargs | MyThinkPond

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?

[sourcecode language=“jscript”]

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…

[/sourcecode]

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.

[sourcecode language=“jscript”]

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

//process personFullName logic here  }

}

[/sourcecode]

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:

[sourcecode language=“jscript”]

public constructorOne(Object… parts){

//your logic here

}

[/sourcecode]

Cheers.

Venkatt Guhesan avatar
About Venkatt Guhesan
Enterprise Software Architect currently working at DataDirect Networks developing a highly scalable monitoring solution called DDN Insight. My passions include all things Open Source including Linux (CentOS, Red Hat, Gentoo, Open Stack, Docker & Ubuntu), embedded ARM processors and microcontrollers (Arduino, UDOO, Cubieboard, BeagleBoard, OnionIO, TI's Zigbee). Coming from an Electrical and Computer Engineering background, working in developing and designing enterprise - distributed, highly scalable software requires a unique set of software skills with a good understanding of the hardware. This makes his work challenging and interesting. In his free time, he spends his time with his family and two children. He also enjoys researching on topics including - world ancient history and yoga. Visit the 'About' section for more details.
comments powered by Disqus