Varargs is a syntactic sugar type feature that allows writing a method that can take a variable number of arguments.
Syntax
public void myMethod(String... messages) {
// Method body
}Usage
myMethod("Hello", "World"); // Two arguments
myMethod("Single message"); // One argument
myMethod(); // No arguments public void printMessages(String... messages) {
for (String msg : messages) {
System.out.println(msg);
}
}Rules
- A method can have at most one vararg parameter
- If a method has other parameters, varargs must be the last one in the method signature
- All arguments passed to varargs must be of the same data type
- Java compiler will automatically convert the variable arguments into an array when the method is called
- if called with no arguments, internal array will have length of 0