Varargs (variable arguments)
is a new feature in Java 1.5 which allows us to pass multiple values in a single variable name when calling a method. Of course, it can be done easily using array but the varargs add another power to the language.
The varargs can be created by using three periods (...
) after the parameter type. If a method accept others parameter than the varargs, the varargs parameter should be the last parameter to the method. And please be aware that overloading a varargs method can make harder to figure out which method is called in the code.
package org.kodejava.lang;
import java.util.Arrays;
public class VarArgsExample {
public static void main(String[] args) {
VarArgsExample e = new VarArgsExample();
e.printParams(1, 2, 3);
e.printParams(10, 20, 30, 40, 50);
e.printParams(100, 200, 300, 400, 500);
}
public void printParams(int... numbers) {
System.out.println(Arrays.toString(numbers));
}
}
Running the code snippet give you the following output:
[1, 2, 3]
[10, 20, 30, 40, 50]
[100, 200, 300, 400, 500]
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024