What do the ... dots in the method parameters mean in java?
What do the ... dots in the method parameters mean in java?
In Java, the three dots (...
) used in method parameters are known as varargs, which stands for variable arguments. This feature allows a method to accept zero or more arguments of a specified type. Varargs can be very useful when you do not know in advance how many arguments will be passed to the method, or if you want the method to handle an arbitrary number of arguments.
When you declare a method with a varargs parameter, you are telling the Java compiler that this method can accept an array of arguments of the specified type. The varargs parameter is always the last parameter in the method's signature. Here's how you can define and use a varargs method:
public void printNumbers(int... numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
In this example, printNumbers
can be called with any number of int
arguments, or even no arguments at all:
printNumbers(1, 2, 3); // prints 1, 2, 3
printNumbers(4, 5, 6, 7); // prints 4, 5, 6, 7
printNumbers(); // prints nothing
...
) followed by the parameter type and the parameter name.Varargs are particularly useful when you need a method to handle a variable number of parameters without overloa...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào