How can variable parameters be passed in Java?
In Java, you can use varargs to achieve variable parameter passing. Use three dots (…) in the method’s parameter list to indicate varargs. For example:
public void printValues(String... values) {
for (String value : values) {
System.out.println(value);
}
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.printValues("value1", "value2", "value3");
}
In the given example, the printValues method takes a variable parameter values, allowing any number of String type arguments to be passed to the method. In the main method, the printValues method is called and three arguments are passed to it. Within the printValues method, the passed parameter values are printed using an enhanced for loop.