Home >Java >javaTutorial >How Do Variable Arguments (Varargs) Work in Java?
Variable Arguments in Java
In Java, the three dots (also known as varargs) following the parameter type, such as in the method below, signify variable arguments:
public void myMethod(String... strings) { // method body }
Meaning
This means that you can pass zero or more String objects (or a single array of them) as arguments to the method. For instance, you can call the method as follows:
myMethod(); // Likely useless, but possible myMethod("one", "two", "three"); myMethod("solo"); myMethod(new String[]{"a", "b", "c"});
Behavior
It's important to note that the arguments passed using varargs are always stored in an array. Even if there's only one argument, it's converted into an array. This behavior must be accommodated in the method body.
Limitations
The parameter that uses varargs must be the last parameter in the method signature. For example, the following method signature is valid:
myMethod(int i, String... strings)
However, the following method signature is invalid:
myMethod(String... strings, int i)
The above is the detailed content of How Do Variable Arguments (Varargs) Work in Java?. For more information, please follow other related articles on the PHP Chinese website!