Introduction To Varargs (Variable Arguments) In Java


In this article, we discuss Varargs (Variable Arguments) in Java.

What is Varargs (Variable Arguments) in Java?

Varargs allow the method to accept zero, one or more arguments. Before varargs either we used an array as the method parameter or use an overloaded method, but using this causes maintenance problems. If we are not sure how many arguments will be passed in the method, then varargs is the better approach.
Using Varargs, we don't need additional overloaded methods so less coding is used.

How Varargs Works in Java?

When initializing the arguments, the compiler starts to match the argument list left-to-right with the given parameters. Once the given set of parameters are matched, then the remaining arguments are passed as an array to the method.
It always uses an ellipsis, in other words, three dots (...) after the data type. The syntax is as follows:
return_type method_name(data_type... variable_Name) {}
1. Example
  1. class VarargsEx1 {  
  2.  static void print(String...values) {  
  3.   System.out.println("invoked print method");  
  4.  }  
  5.  public static void main(String args[]) {  
  6.   print();  
  7.   print("welcome""to""java""world");  
  8.  }  
  9. }  
2. Example
  1. class VarargsEx2 {  
  2.  static void print(String...values) {  
  3.   System.out.println("invoked print method");  
  4.   for (String str: values) {  
  5.    System.out.println(str);  
  6.   }  
  7.  }  
  8.  public static void main(String args[]) {  
  9.   print();  
  10.   print("welcome");  
  11.   print("welcome""to""java""world");  
  12.  }  
  13. }  
Rules for varargs
There are some rules for varargs that we must follow, otherwise, the code can't compile. They are:
  1. Specify the type of the arguments (can be primitive or Object).
  2. Use the (…) syntax.
  3. You can have other arguments with varargs.
  4. There can be only one variable argument in the method.
  5. Variable arguments (varargs) must be the last argument.
3. Example
This example shows last the argument in the method.
  1. class VarargsEx3 {  
  2.  static void print(int n, String...values) {  
  3.   System.out.println("The no. is " + n);  
  4.   for (String str: values) {  
  5.    System.out.println(str);  
  6.   }  
  7.  }  
  8.  public static void main(String args[]) {  
  9.   print(25"hello");  
  10.   print(50"welcome""to""java""world");  
  11.  }  
  12. }  

Similar Articles