What is Varargs method in java?

Variable list of arguments(Var-arg) methods is the most important concept introduced in java 1.5 version. The main purpose of this Var-args methods is to increase the usability of a method by allowing any number of arguments in the method call. Best example of varargs method is main method

public static void main(String[] args) is same as ...
public static void main(String... args)

Var-arg is indicated using three sequential dots ( "..." ) .
Example:
method(int... args); // accepts any number of arguments of type int.
m1(String... args); // accepts any number of arguments of type String.
We can pass any number of arguments to the varargs methods including zero. Let us see how we can declare and call a var-arg method.
package com.programmerQueries.java.Varagrs;

/**
 * @author ProgrammerQueries
 * @since: 22-04-2017
 */
public class VarargApp
{
    public static void main( String[] args )
    {
        m1();
        m1(1);
        m1(1,2);
       
    }
    public static void m1(int... args)
    {
        System.out.println( "Programmer Queries!" );
    }
Output

The above example contains a vararg method  m1.We can pass any number of arguments to the method m1 . All the 3 method calls in the above program are valid.
The var-arg parameters are converted to one dimentional array internally.Hence the var-arg values can be differentiated using index.





 



No comments:

Post a Comment