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
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.