Skip to content
Related Articles

Related Articles

Improve Article

Overloading Variable Arity Method in Java

  • Last Updated : 20 Jul, 2021

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 paramaters 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);
    }
}
Output
Sum : 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 maethod 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 ype
    // 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);
    }
}
Output



varargs 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();
    }
}
Output
varargs 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(int…y).
  • 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,

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :