Varargs:- Variable argument method in Java 5

February 16, 2011 by Sandeep Bhardwaj | Tags:


Varargs enables to write methods which can takes variable length of arguments.Varargs was added in Java 5 and the syntax includes three dots … provides the functionality to pass any number of arguments to a method.

Syntax

public void showDepartmentEmp(int deptCode, String... deptEmp){}

Example

public class Department {

    public static void main(String args[]) {
     showDepartmentEmp(100, "Sandeep", "Gaurav");
     showDepartmentEmp(111, "Meenakshi", "Aditya", "Saurabh");
    }

    public static void showDepartmentEmp(int deptCode, String... deptEmp) {
        System.out.print("\n"+deptCode);
        for(String emp: deptEmp) {
            System.out.print(", " + emp);
        }
    }
}