What are variable arguments(varargs)?
Variable arguments is a feature in Java that allows us to create methods that can accept zero or multiple number of arguments
of a specified type. Before java 5, you could not declare a method with a variable number of arguments. If the number of arguments for the method were to change then you would need to declare a new method.
For example,
public void aMethod(int a)
{
//some method body
}
the function aMethod has only one argument. Say we wanted to call **aMethod **with more than one argument, the options we would have was to create overloaded methods, pass an array as an argument or declare a new method with the number of arguments needed.
In the event where we do not know the number of arguments that are going to be passed a better approach would be to use the varargs feature.
Varargs implementation
The syntax for declaring a method with variable arguments is using the ellipses notation("...") after the datatype. Internally this feature is implemented as an array, so you would handle the varargs the same way you would handle an array
Below is the syntax
public void aMethod(String... arguments)
{
for (String argument : arguments)
{
// some code handling
}
}
Now for a practical example.
Imagine you are planning a party and you want to gather preferences from your friends regarding the food they would like to have. Each friend may have a different number of food options they want to suggest. Varargs can be used in this scenario to handle the varying number of suggestions from each person.
Implementing this in code will look like this
public static void gatherFoodPreferences(String... foodOptions) {
System.out.println("Food preferences:");
for (String option : options) {
System.out.println("- " + option);
}
}
We can call this method with a different number of arguments depending on the options each person suggests
gatherFoodPreferences("Pizza", "Burger");
gatherFoodPreferences("Pasta", "Fried rice", "Fried Chicken");
The method will iterate over each argument and print out each food option. This allows us to gather different opinions and options without having to explicitly define the exact number of options upfront.
Some rules to note when implementing varargs
- You can only have one variable argument in a method.
- If there are other arguments in the method the variable argument has to be declared as the last argument.
Top comments (0)