Method With varargs in Java


This Java program defines a public class called MethodArgs which contains two methods: getNames and main. The getNames method is declared with a variable-length argument list using the ellipsis (...) notation, which allows the method to accept any number of arguments of type String.

In the implementation of the getNames method, a for-each loop is used to iterate through the names array and print each element to the console. The main method serves as the entry point for the program. In this method, the getNames method is called with five string arguments: "Ram", "Sam", "Ravi", "Kumar", and "sara".

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