Introduction
In this article, we discuss Varargs (Variable Arguments) in Java.
What is Varargs (Variable Arguments) in Java?
Varargs allow the method to accept zero, one or more arguments. Before varargs either we used an array as the method parameter or use an overloaded method, but using this causes maintenance problems. If we are not sure how many arguments will be passed in the method, then varargs is the better approach.
Using Varargs, we don't need additional overloaded methods so less coding is used.
How Varargs Works in Java?
When initializing the arguments, the compiler starts to match the argument list left-to-right with the given parameters. Once the given set of parameters are matched, then the remaining arguments are passed as an array to the method.
Syntax
It always uses an ellipsis, in other words, three dots (...) after the data type. The syntax is as follows:
return_type method_name(data_type... variable_Name) {}
1. Example
- class VarargsEx1 {
- static void print(String...values) {
- System.out.println("invoked print method");
- }
- public static void main(String args[]) {
- print();
- print("welcome", "to", "java", "world");
- }
- }
Output
2. Example
- class VarargsEx2 {
- static void print(String...values) {
- System.out.println("invoked print method");
- for (String str: values) {
- System.out.println(str);
- }
- }
- public static void main(String args[]) {
- print();
- print("welcome");
- print("welcome", "to", "java", "world");
- }
- }
Output
Rules for varargs
There are some rules for varargs that we must follow, otherwise, the code can't compile. They are:
- Specify the type of the arguments (can be primitive or Object).
- Use the (…) syntax.
- You can have other arguments with varargs.
- There can be only one variable argument in the method.
- Variable arguments (varargs) must be the last argument.
3. Example
This example shows last the argument in the method.
- class VarargsEx3 {
- static void print(int n, String...values) {
- System.out.println("The no. is " + n);
- for (String str: values) {
- System.out.println(str);
- }
- }
- public static void main(String args[]) {
- print(25, "hello");
- print(50, "welcome", "to", "java", "world");
- }
- }
Output