Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Types of Var-arg Rules in Java

DZone's Guide to

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
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

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 }}