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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,core java ,core java interview question

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}