All About Methods with Varagrs in Java

0
30
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

All About Methods with Varagrs in Java
All About Methods with Varagrs in Java

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","[email protected]");
}
}

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

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here