Over a million developers have joined DZone.

Types of Var-arg Rules in Java

When writing methods using var-args, we may confuse different scenarios, like where to put var-args in the parameters and how to place different type of arguments.

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

While writing methods using variable arguments(var-args), we may confuse different scenarios, like where to put var-args in the parameters and how to place different type of arguments. Here we have some rules with scenarios to easily understand.


This will help you in the SCJP examination and as well, java interviews for freshers and experienced guys.

Rule 1: 

Var-arg syntax is allow only for method parameters not for normal variables.

public void add(int...a)
int... a; //compiler time error

Rule 2: 

Var-arg syntax is allowed only after parameter type and just before parameter name but it is not allowed after parameter name.

Ex: 

public void add(int...a){}
public void multiply(long... l){}
public void add(int a...){} //not valid syntax

Rule 3: 

Since var-arg is a single dimensional array parameter. We were not allowed to overload the method with the same array([]) parameter type, it leads to compile time error.

Ex: 

public void add(int...a){}
public void add(int[] a){} //Duplicate method add(int[]) in type VarArgsCases

Here both arguments types are same.

Rule 4: 

Var-arg parameter must be last parameter in the list else it leads to compile time error.']' expected. 

For more Rule of Var-Args in Java 

Ex: 

void add(int a,float... b){
void add(int a,float b,long... c){} // compile time error
void add(int...a, float b,long c){} //compile time error

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
java ,core java ,core java interview question

Published at DZone with permission of Das Nic. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}