Java-Variable Length Arguments(Method Overloading)

Variable Length Arguments (Method Overloading)

Just like normal methods, java  provides facility to overload vararg methods also. You can overload a method with a variable length arguments as long as the parameters for the methods differ in type or order. For example :

void varArgsTest(int...v){}

void varArgsTest(boolean...v){}

void varArgsTest(String...v){}

The types of its varargs parameter can differ. This is the case for varArgsTest(int …), varArgsTest(boolean…), and varArgsTest(String…). The parameter to be treated as an array of the specified type. Therefore, just as you can overload methods by using different types of array parameters, you can overload varargs methods by using different types of varargs.

Program

1

Program Source

class VarArgsTest {
    
    void varArgsTest(int...v)
    {
        System.out.println("Integer Arguments length is : "+v.length);
        for(int x : v)
        {
            System.out.println("Argument : "+x);
        }
    }
    
    void varArgsTest(boolean...v)
    {
        System.out.println("Boolean Arguments length is : "+v.length);
        for(boolean x : v)
        {
            System.out.println("Argument : "+x);
        }
    }
    
    void varArgsTest(String...v)
    {
        System.out.println("String Arguments length is : "+v.length);
        for(String x : v)
        {
            System.out.println("Argument : "+x);
        }
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        VarArgsTest vrtest = new VarArgsTest();
        vrtest.varArgsTest(10,20,30);
        vrtest.varArgsTest(true,false,true,false);
        vrtest.varArgsTest("One","Two","Three","Four","Five");
    }
}

Leave a Comment