What is variable length argument?

Variable length argument used for remove the problem of method overloading concept means we can pass the value to the method parameter according to programmer need without changing the code or parameter. Variable length argument internaly implemented as 1D array.

How to use variable length argument?

Put three dots in method

Syntax


    return_typr method_name(data_type ...variable_name)
    {
    }
	
    return_typr method_name(data_type... variable_name) //invalid declaration
    {
    
    }
    

Some Point to be remember.

If there are more than one parameter available than variable length arguments must be declare at the last.


    public void m1(int a, int b, ...b)
    {
    }

Only one variable length argument available in the method parameter list.

Example of variable length argument


    class Book
	{
		public void m1(int ...a)
		{
			for(int i=0; i<a.length; i++)
			{
			System.out.print(" "+a[i]);
			}
		}
	}
		class Test
		{
		public static void main(String args[])
		{
		Book b = new Book();
		b.m1(1,2,3,4,5);
		}
	}

Output


	C:\Users\Nature\Desktop\Java>java Test
	 1 2 3 4 5

Advertisement here

Share this Page.