Javatpoint Logo
Javatpoint Logo

Variable Argument (Varargs):

The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach.

Advantage of Varargs:

We don't have to provide overloaded methods so less code.


Syntax of varargs:

The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:


Simple Example of Varargs in java:

Test it Now
Output:display method invoked
       display method invoked

Another Program of Varargs in java:

Test it Now
Output:display method invoked
       display method invoked
       hello
       display method invoked
       my
       name
       is 
       varargs


Rules for varargs:

While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows:

  • There can be only one variable argument in the method.
  • Variable argument (varargs) must be the last argument.

Examples of varargs that fails to compile:

Example of Varargs that is the last argument in the method:

Test it Now
Output:number is 500
       hello
       number is 1000
       my
       name
       is 
       varargs




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials