Overloading Variable Arity Method in Java
Last Updated :
12 Sep, 2022
Here we will be discussing the varargs / variable arity method and how we can overload this type of method. So let us first understand what a variable arity method is and its syntax. A variable arity method also called as varargs method, can take a number of variables of the specified type.
Note: Until version 1.4 there is no varargs method. It was introduced in version 1.5 and exists onwards.
Syntax:
methodName(dataType...variableName)
" ... " means the method can take any number of arguments of the specified data type, even zero. Internally varargs method is implemented using a single dimension(1D) array concept.
Example 1:
Java
// Java Program to Illustrate Variable arity Method
// Importing required classes
import java.io.*;
// Main class
class GFG {
// Method 1
// Main driver method
public static void main(String[] args)
{
// Calling varargs sum method with no parameter
sum();
// Calling varargs sum method with two int type
// parameters
sum(10, 10);
// Calling varargs sum method with three int type
// parameters
sum(15, 15, 20);
}
// Method 2
// varargs method expects zero or
// more int type parameters
public static void sum(int... x)
{
int total = 0;
// Takes parameters passed to sum, one at a time
// later summing it up
for (int y : x) {
total += y;
}
// Print the sum on console
System.out.println("Sum : " + total);
}
}
OutputSum : 0
Sum : 20
Sum : 50
Now let us have a look at few important facts about the varargs method and the acceptable order of parameters. The following points will help to improve the understanding of the varargs method which are as follows:
1.1 Varargs parameters can be mixed with normal parameters.
methodName(int x, String...y)
methodName(10) | Valid |
---|
methodName(10 , "Hello") | Valid |
---|
1.2 During mixing, varargs parameter should be last
methodName(int x, String...y) | valid |
---|
methodName(int...x, String y) | invalid |
---|
1.3 There can only be one vararg parameter
methodName(int x, int y, String...z) | valid |
---|
methodName(int...x, String...y) | invalid |
---|
1.4 In general, varargs method will get the last priority means if no other method is matched then only varargs method will be called. The following example will sail across this concept.
Example:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
sum(9);
// Since we are passing two int type arguments and
// we have defined a function which expects two int
// type parameters so that particular method (normal
// sum method ) will be called and not varargs
// method.
sum(10, 20);
}
// normal method which expects two int type parameters
public static void sum(int x, int y)
{
System.out.println("normal method");
System.out.println("Sum : " + (x + y));
}
// varargs method which expects zero or more int type
// parameters
public static void sum(int... x)
{
System.out.println("varargs method");
int total = 0;
for (int y : x) {
total += y;
}
System.out.println("Sum : " + total);
}
}
Outputvarargs method
Sum : 9
normal method
Sum : 30
1.5 Using arrays to pass the variable number of arguments is an old approach to varargs, which is not suitable.
So let us do discuss the overloading varargs method. We know that if a class has multiple methods having the same name but different parameters, it is known as Method Overloading. The same is valid for varargs method also. Let us implement the same
Implementation: Here 'vaTest' is overloaded as each occurrence of vaTest expects a different argument list. Which occurrence of vaTest will be called to execute the operations on the parameters depends on the type of each parameter.
Example:
Java
// Java Program to illustrate Overloading in Variable
// arity
// Importing input output classes
import java.io.*;
class GFG {
public static void main(String[] args)
{
vaTest(1, 2, 3, 4, 5);
vaTest(true, true, false, true);
vaTest("Message", 10, 20);
}
// Method 1
// varargs method which expects zero or
// more int type parameters
public static void vaTest(int... x)
{
// Print statement on console
System.out.println(
"varargs method with int type arguments");
for (int y : x) {
System.out.print(" " + y);
}
System.out.println();
}
// Method 3
// varargs method which expects zero or
// more boolean type parameters
public static void vaTest(boolean... x)
{
// Print statement on console
System.out.println(
"varargs method with boolean type arguments");
for (boolean y : x) {
System.out.print(" " + y);
}
System.out.println();
}
// Method 3
// varargs() method which expects first parameter to be
// of String type and then zero or more int type
// parameters.
public static void vaTest(String msg, int... x)
{
// Print statement on console
System.out.print(msg);
for (int y : x) {
System.out.print(" " + y);
}
// New line
System.out.println();
}
}
Outputvarargs method with int type arguments
1 2 3 4 5
varargs method with boolean type arguments
true true false true
Message 10 20
Note: A vararg method can also be overloaded by the non-varargs method. vaTest(boolean x) is valid to overload vaTest. This vaTest(boolean x) will be invoked only if one boolean argument is passed, otherwise (boolean...x).
Ambiguities: There also do occurs some ambiguities as listed:
- Call to vaTest is ambiguous because varargs can be empty and hence this call can be equally translated to either vaTest(int...x) or vaTest(boolean...x).
- Let us suppose we have two methods , vaTest(int...x) and vaTest(int a, int...x) . Now , if we call vaTest(1) , both formats are valid. Therefore ambiguity,
Similar Reads
Method Overloading in Java
In Java, Method Overloading allows us to define multiple methods with the same name but different parameters within a class. This difference can be in the number of parameters, the types of parameters, or the order of those parameters.Method overloading in Java is also known as Compile-time Polymorp
10 min read
Method Overloading and Ambiguity in Varargs in Java
Prerequisite - Varargs , Method Overloading Method Overloading in Varargs Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. We can overload a method that takes a variable-leng
5 min read
Different Ways of Method Overloading in Java
In Java, Method overloading refers to the ability to define multiple methods with the same name but with different parameter lists in the same class. It improves code readability and reusability, Instead of assigning different names to methods performing similar operations, we can use the same name,
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters
4 min read
Scope of Variables in Java
The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about
7 min read
ValueRange of() method in Java with Examples
The of() method of ValueRange class helps us to Obtains value range based on parameters passed to it. There are three types of of() methods based on parameters passed to it. of(long min, long max): This method help us to get a fixed value range where the minimum and maximum values are fixed. Syntax:
3 min read
Final Static Variable in Java
When the value of a variable is not varied, then it is not a good choice to go for an instance variable. At that time, we can add a static modifier to that variable. Whenever we declare a variable as static, then at the class level, a single variable is created which is shared with the objects. Any
3 min read
Final Local Variables in Java
In Java, a local variable is a variable, which is declared inside a method. Local variables are only accessible within the method in which they are declared, other methods in the class do not know anything about that variable. When we declare a local variable, we need to initialize it first before u
3 min read
Static Variables in Java
In Java, when a variable is declared with the static keyword. Then, a single variable is created and shared among all the objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable. These are the main scenarios when we u
3 min read
Year atMonthDay() method in Java
The atMonthDay(MonthDay) method of Year class in Java combines the current year object with a month-day object passed as parameter to it to create a LocalDate object. Syntax: public LocalDate atMonthDay(MonthDay monthDay) Parameter: This method accepts a single parameter monthDay. It is the MonthDay
2 min read