What are variable length arguments?

Are you preparing for IT certification? With practice questions, study notes, interactive quizzes, tips and technical articles, uCertify PrepKits ensure that you get a solid grasp of core technical concepts to ace your certification exam in first attempt.

What are variable length arguments?

Rating:

Variable length arguments are used to declare a method that takes a variable number of arguments. This is one of the features added in the J2SE 5 version. Varargs are declared using a data type followed by three periods (...). An example of variable length arguments is as follows:

public void amethod(int...i)

Here, i represents an array of integers.

A method with a normal parameter can be written along with a variable length argument, the condition being that the varargs parameter should be the last parameter in the method. The following will throw a compile-time exception:

int amethod(int...amethod, float f)

Instead, it should be written as follows:

int amethod(float f, int...amethod)

Moreover, two variable length arguments cannot be written in one method. The example given below is incorrect:

int amethod(int...i, double... j)

Like any other method, a method with a varargs parameter can also be overloaded. However, it should be used with proper caution, as it may sometimes create ambiguity. For example, in the following syntaxes int amethod(int i,int...j) and int amethod(int i), if the length of the varargs parameter is zero, the compiler will never know which version of amethod() is being called, as both will be equivalent to int amethod(int i).


Rating:



Other articles

Click here to Article home

 
uCertify.com | Our Company | Articles | Privacy | Security | Contact Us | News and Press Release | uCertify India
MCSE: MCSA, MCTS, MCITP    JAVA Certification: SCJP, SCWCD Cisco Certification: CCNA, CCENT, A+, Network+, Security+
Oracle Certification: OCP 9i, OCP 10g, OCA 9i, OCA 10g CIW foundation    EC-212-32    CISSP    Photoshop ACE    Adobe Flash ACE
© 2008 uCertify.com. All rights reserved. All trademarks are the property of their respective owners.