What is variable length argument in Java?

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

How to use variable length argument in Java?

To use the variable length argument in program you have to put three dots in method parameter before the variable name and after data type.

Syntax of variable length argument:


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

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

Post Your Comment