Variable arguments or varargs methods in java

Java variable arguments was introduced in java 5 and it allows methods to take as many number of arguments you want.

Syntax:

We use three dots (...) also known as ellipsis to define variable arguments.
public  void method (String a,int ... b)
 {
  
 }
There are some points which you need to keep in mind while using varargs methods:
  1. You can have only one variable arguments (ellipsis) in one method
  2. varargs should be last parameter in the method, otherwise method won't compile.

Why to use variable arguments or varargs methods: 

There are two alternatives which can be used which developers used before java 1.5
  1. Method overloading
  2. Passing array to the method
Method overloading may not be good idea because you don't know number of methods you need to overload.You can pass arguments in the array but why don't we can directly use varargs method and let compiler create array for us.

How varargs works internally.

While invoking varargs method, compiler matches argument from left to right, Once fixed number of arguments are matched, rest all arguments are created as array and passed to method.

For example:
Lets say you have method signature as below:
public  void method (String a,int b,int ... c)
 {
  
 }
and you invoke this method as
method("test",1,2,3,4)
then "test" and 1 will be passed as normal parameters and 2,3 and 4 will be passed as array.

Java variable arguments or varargs example:

package org.arpit.java2blog;

public class VarArgsMainJava {

 public static void main(String[] args) {
 
  method("test",1,2,3,4,5);
  anotherMethod(10,20,30,40,50);
 }
 
 public  static void method (String a,int b,int ... c)
 {
  System.out.println("Method arguments are");
  System.out.print(a);
  System.out.print(" "+b);
  for (int i = 0; i < c.length; i++) {
   System.out.print(" "+c[i]);
  }
  System.out.println();
 }
 
 public  static void anotherMethod (int b,int ... c)
 {
  System.out.println("Method arguments are");
  System.out.print(b);
  for (int i = 0; i < c.length; i++) {
   System.out.print(" "+c[i]);
  }
 }

}

When you run above program, you will get below output:
Method arguments are
test 1 2 3 4 5
Method arguments are
10 20 30 40 50

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012