Social Media

Tag Archives for " varargs "

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]