How To Use Varargs Variable Argument Methods.

Until 1.4 version we can’t declare a method with variable number of arguments. If there is a change in number of arguments compulsory we should go for new method. It increases length of the code and reduce readability. To overcome this problem sun people introduce var-arg methods in 1.5 version, according to this we can declare a method which can take variable number of arguments. Such type of methods are called var-arg methods.

Syntax

Method_Name(parameter_type…)

We can declare a var-arg method as follows

M1(int… x)

We can call this method by any number of argument.

Example

Output

Internally var-arg parameter will be converted into one dimensional array hence within the var-arg method we can differentiate values by using index.

You can learn this in detail in our institute which provides advance Java training in Delhi and Core java training in Delhi.

Some possibilities and not allowed syntax in var-arg method

  1. We can mix var-arg parameter with normal parameter. Example

Output

  1. Inside var-arg method we can take only one var-arg parameter and we can’t take more than one var-arg Example

Output

  1. If we mix var-arg parameter with normal parameter then var-arg parameter should be last parameter.

Example

Output

In this example we use var-arg parameter before String type parameter so we will get compile time error.

Output

 

In this example we use String type var-arg method after char type parameter so this works fine

  1. Inside a class we can’t declare var-arg method and corresponding one dimensional array method simultaneously otherwise we will get compile time error.

Output

Small Notes About java:-

Java is a general purpose, object-oriented programming language. Latest version is Java 9, released on September 21,2017 has various functionalities. We are just discuss var-arg parameter today, Codec Networks provides best Java Training & Certification in Delhi.

About

Codec Networks provides IT Trainings from EC Council CEH ECSA, LPT, CHFI, Network Security, Penetration Testing, ISACA, ISC2, PECB ISO 27001LA LI, Cisco Networking CCNA CCNP, Linux Administration RHCE, Prog Languages JAVA, Advanced Java, android development. We also offer B2B Industry Solutions and Services in IT | Information|Cyber Security in Delhi NCR India.

View all posts by