Variable Argument In Java
Variable Argument
In Java, the variable argument (varrags) permits the method to accept zero or multiple arguments. Before variable argument, we either use overloaded method or receive an array as the method parameter but it was not considered good because it creates the maintenance problem. If we don't know how many arguments, we will have to pass in the method then variable argument is the better approach.
We don't have to provide overloaded methods. Thus, less coding is involved.
Syntax
The variable argument uses ellipsis i.e. three dots after the data type.
return_type method_name(data_type... variableName){}
Rules for Variable Argument
While using the variable argument, we must follow some rules otherwise the program code won't compile. The rules are,
- Only one variable argument can be included in the method.
- Variable argument should be the last argument.
Examples of variable argument that fails to compile are,
void method(String... x, int... y){}
void method(int... x, String y){}
Let’s see an example, given below.
Code
- public class VariableArgs {
- static void print(String...values) {
- System.out.println("Print method called.. ");
- }
- public static void main(String args[]) {
- print();
- print("I", "am", "Variable", "Argument");
- }
- }
Output
Let’s see another example, given below.
Code
- public class VariableArgs {
- static void print(String...values) {
- System.out.println("Print method called.. ");
- for (String s: values) {
- System.out.println(s);
- }
- }
- public static void main(String args[]) {
- print();
- print("hello");
- print("I", "am", "Variable", "Argument");
- }
- }
Output
Let’s see another example, given below.
Code
- public class VariableArgs {
- static void print(int n, String...values) {
- System.out.println("Number is :" + n);
- for (String s: values) {
- System.out.println(s);
- }
- }
- public static void main(String args[]) {
- print(1, "hello");
- print(2, "I", "am", "Variable", "Argument");
- }
- }
Output
Summary
Thus, we learnt that the variable argument (varrags) permits the method to accept zero or multiple arguments and also learnt its important rules in Java.