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

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

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

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}