Method With varargs in Java


Using varargs as a parameter for a method definition, it is possible to pass either an array or a sequence of arguments. If a sequence of arguments is passed, they are converted into an array automatically. The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position.

Example :
      shows both an array and a sequence of arguments being passed into the getNames() method, and how they are treated identically in the code inside the method:.

Source Code

public class MethodArgs {
    //Method With Varargs in Java
    public static void getNames(String... names) {
        for (String name : names)
            System.out.println(name);
    }
 
    public static void main(String args[]) {
        getNames("Ram", "Sam", "Ravi", "Kumar", "sara");
    }
}
 

Output

Ram
Sam
Ravi
Kumar
sara
To download raw file Click Here

Basic Programs