All About Methods with Varagrs in Java



In this post, I have discussed regarding methods in Java. Varargs represents variable length arguments in method. This makes java simple yet very powerful. 
The general syntax is given as:

<access specifier><return type>methodName(<argument type>... arguments)
 
This method contains an argument referred as varargs in which we are going to pass the specific type of arguments.
An ellipsis(...) is the key to varargs and argument is the name of the variable.

public void registration(String userName,String password,String emailId);
//can be written as:
public void registration(String... registrationDetails)
 
String... registrationDetails specifies that we can pass any number of String arguments to the registration() method.
How to retrieve the values:

class Registration{
testVarargs(String... registrationDetails)
{
for(String details:registrationDetails)
{
System.out.println(details);
}
} 
public static void main(String args[])
{
testVarargs("MydigitalVoice","abc123","hello@mydigitalvoice.in");
}
}
 
At compile time the String... registrationDetails is converted to String[] varargs. we can pass any array of Strings to the methods.Varargs does not generate any compile time errors even if an empty argument is passed as a parameter to the method
All About Methods with Varagrs in Java All About Methods with Varagrs in Java Reviewed by Animesh Chatterjee on December 15, 2018 Rating: 5

No comments:

Powered by Blogger.