Explain about Varargs in java?

Java 8Object Oriented ProgrammingProgramming

Since JSE1.5 you can pass a variable number of values as argument to a method. These arguments are known as var args and they are represented by three dots (…)

Syntax

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

Example

In the following example, the method named sample() accepts varargs (of type String) and from the main method, we are invoking this method multiple times by passing a different number of arguments each time we invoke it.

public class VarargsExample{
   void sample(String... args) {
      for (String arg: args) {
         System.out.println(arg);
      }
   }
   public static void main(String args[] ){
      VarargsExample obj = new VarargsExample();
      obj.sample("Ram", "Rahim", "Robert");
      obj.sample("Krishna", "Kasyap");
      obj.demoMethod("Vanaja");
   }
}

Output

Ram
Rahim
Robert
Krishna
Kasyap
Vanaja

When to use − Whenever, you want to pass different number of arguments each time you call a method you should use vararg methods.

Example

In the following example the sample() method accepts varargs of type integer and from the main method we are invoking this method multiple times and, we are passing different number of integer arguments each time we invoke it.

 Live Demo

public class VarargsExample{
   void demoMethod(int... args) {
      for (int arg: args) {
         System.out.println(arg);
      }
   }
   public static void main(String args[] ){
      VarargsExample obj = new VarargsExample();
      obj.demoMethod(1101, 10225, 26);
      obj.demoMethod(22365, 12);
      obj.demoMethod(1);
   }
}

Output

1101
10225
26
22365
12
1
raja
Published on 05-Jul-2019 13:57:16
Advertisements