A Brief Introduction To var arg Method in Java

Posted By Nanda Ram | 31-Jan-2018
Until 1.4 version we can not declare a method with a variable number of argument if there will be any variation in a number of argument compulsory we should declare a new method. this approach increases the line of the code and reduces readability. To resolve these problem sun people introduced var-arg methods in 1.5 version. hence from 1.5 version onward we can declare a method with a variable number of argument this type of method is known as var-arg methods.
 
We can declare var-arg method as follows.
 m1(int... a)
 In this method m1() we can pass any number of integer values or invoke it by passing any number of integer values.
 Example 
class Simple 
		 {
		  public static void display(int... i)
		  {
		  System.out.println(" this is var - arg method");
		 }
		 public static void main(String... args)
		 {
		 display();
		 display(10,20);
		 display(10);
		 display(10,20,30,40);
	   } 
}
output:
       this is var - arg method
	   this is var - arg method
	   this is var - arg method
	   this is var - arg method
The internally var-arg method is implemented with the help of single dimensions arrays concept. hence in the var-arg method, we can differentiate arguments by using the index.
 Example  
 class Simple 
		 {
		  public static void addition(int... n)
		 {
		   int a =0;
		  for(int y:n){
		 {
		  a = a +y;
		 }
		  System.out.println("The Addition is:"+a);
		 }
		 public static void main(String... args)
		 {
		 addition();
		 addition(10,20);
		 addition(10,20,30);
		 addition(10,20,30,40);
	   }
}
output:
        The Addition is:0
		The Addition is:30
		The Addition is:60
		The Addition is:100
Case(1):
 Which of the followings var-arg method declaration is valid.
subtract(int... x)   // This is valid
subtract(int x...)   // This is not valid
subtract(int ...x)   // This is valid
subtract(int. ..x)   // This is not valid
subtract(int .x..)   // This is not valid
 
Case(2):
In the var-arg method, we can combine var-arg parameters as well as a normal parameter also.
     subtract(int x, String... y)
 
Case(3):
 If we are declaring a general parameter with var-arg parameter then var-arg parameter must/should be the last parameter.
sum(int... x, String y)   // This is not valid
sum(int x, String... y)   // This is valid
 
Case(4):
In any var-arg method, we can have an only single var-arg parameter.
subtract(int... a, String... b)  // This is not valid
subtract(int a, String... b)   // This is valid
Request for Proposal

Recaptcha is required.

Sending message..