Varargs in Java 5
Varargs means variable arguments, something really different from normal Java language syntax. Normally, we define method signature to offer a contract to the callers of that method by restricting number and type of input parameters, return data type and exceptions thrown. Using vararg feature, we can overcome this restriction partially and make the signature dynamic. You may say that the dynamic signature is not new. Following two options you used many times to avoid an impact on clients due to additional/reduced parameters in signatures.
- Using array/collection as an input parameter
- Using object encapsulating many attributes as an input parameter
Now Java language itself offers the vararg feature to allow variable input parameters. It is not so matured to apply in any scenario; still it can be used in many obvious cases.
Let us take the first most commonly used Java method to demonstrate how it works. We use this code snippet to understand this concept further.
//main method without varargs
public class MainMethodWithoutVarargs {
public static void main(String[] args) {
System.out.println("Method without Varargs");
}
}
//main method with varargs
public class MethodWithVarargs {
public static void main(String... strings) {
System.out.println("Method with Varargs");
MethodWithVarargs mwv = new MethodWithVarargs();
System.out.println("Method call with Varargs " + mwv.getString(1, " First ", " Second "));
}
private String getString (int count, String...strings){
return count + strings[0]+ strings[1];
}
}
The difference in above two main methods can be seen clearly where we use varargs of type String in second main method. Second method ‘getString’ is used to explain how to call a varargs method.
If you have used Jsp technology, then you might have already used this conversion of String attributes in an array feature while passing values of multiple selected checkboxes.
Limitation of Varargs:
- Varargs can be used as a last input parameter. In above example, we cannot use the String vararg before the int input parameter.
- If there are no input values of the varargs type input parameter then there must be at least one “null” value to succeed compilation.
Examples of Java APIs Using Varargs:
- MessageFormat.format
- System.out.printf
- Reflection APIs
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.
