What are variable arguments in java?


While defining a method, In general, we will specify the arguments it accepts along with the type as −

myMethod(int a, String b){
}

Suppose if you need to accept more than one variable of the same type you need to specify the variables one after the other as −

myMethod(int a, int b, int c){
}

You can also pass a variable number of arguments of a particular type, to a method. These are known as variable arguments or, varargs. They are represented by three dots (…)

Syntax

public myMethod(int ... a) {
   // method body
}

Once you use variable arguments as a parameter method while calling you can pass as many numbers of arguments to this method (variable number of arguments) or, you can simply call this method without passing any arguments.

Example

 Live Demo

public class Sample{
   void demomethod(String... args) {
      for (String arg : args) {
         System.out.println(arg);
      }
   }
   public static void main(String args[] ){
      new Sample().demomethod("Ram", "Rahim", "Robert");
      new Sample().demomethod("Krishna", "Kasyap");
      new Sample().demomethod();
   }
}

Output

Ram
Rahim
Robert
Krishna
Kasyap

Example

 Live Demo

public class VarargsExample{
   void demoMethod(String name, int age, int... marks) {
      System.out.println();
      System.out.println("Name: "+name);
      System.out.println("Age: "+age);
      System.out.print("Marks: ");
      for (int m: marks) {
         System.out.print(m+" ");
      }
   }
   public static void main(String args[] ){
      VarargsExample obj = new VarargsExample();
      obj.demoMethod("Krishna", 23, 90, 95, 80, 69 );
      obj.demoMethod("Vishnu", 22, 91, 75, 94 );
      obj.demoMethod("Kasyap", 25, 85, 82);
      obj.demoMethod("Vani", 25, 93);
   }
}

Output

Name: Krishna
Age: 23
Marks: 90 95 80 69
Name: Vishnu
Age: 22
Marks: 91 75 94
Name: Kasyap
Age: 25
Marks: 85 82
Name: Vani
Age: 25
Marks: 93

Rules to follow while using varargs in Java −

  • We can have only one variable argument per method. If you try to use more than one variable arguments a compile-time error is generated.

  • In the list of arguments of a method, varargs must be the last one. Else a compile-time error will be generated.

raja
Published on 12-Sep-2019 09:49:50
Advertisements