Social Media

Varargs …

Varargs were introduced in Java 1.5. They allow you to add a list of parameters to a method as long as they have the same return type.

For example –

[sourcecode language=”java”] class VarArgsExample {
   public static int totalVarArgs(int… intValues) {
      int total = 0;
      for (int n : intValues) {
           total += n;
      }
   }
   public static void main(String[] args) {
      System.out.println("totalVarArgs(1, 2, 3) – " + totalVarArgs(1, 2, 3));
   }  
}
[/sourcecode]

Output –

totalVarArgs(1, 2, 3) – 6

The main rule on varargs is –

  • The vararg variable goes on the end. This means you can only have one vararg –
  • public void getInt(String… varargString, int… varargInt ) {}

Other quirks –

  • Length –
[sourcecode language=”java”] public void getVarargSize(int… intArray) {
   int i = intArray.length;  
}
[/sourcecode]
  • Overriding – you cant do this as there will be a clash –
[sourcecode language=”java”]  public void getInt(int[] intArray) {}
 public void getInt(int… intArray ) {}
[/sourcecode]

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment: