Java-Variable Length Arguments

Variable Length Arguments

If you don’t know how many argument we will have to pass in the method, varargs[Variable-Length Arguments] is the easy approach. Using this technique you can send as many as parameters of the same type without any restriction. For example, in the following program, inside varArgsTest( ), v is operated on as an array. This is because v is an array. The syntax simply tells the compiler that a variable number of arguments will be used, and that these arguments will be stored in the array referred to by v. Then, in main( ), varArgsTest( ) is called with 5 numbers of arguments. The arguments are automatically put in an array and passed to v. In the case of no arguments, the length of the array is zero.

Program

1

Program Source

class VarArgsTest {
    
    void varArgsTest(int...v)
    {
        System.out.println("Arguments length is : "+v.length);
        for(int 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,40,50);
    }
}

 


Leave a Comment