Methods with a Variable Number of Parameters Core Java

Before Java SE 5.0, every Java method had a fixed number of parameters. However, it is now possible to provide methods that can be called with a variable number of parameters.

(These are sometimes called “varargs” methods.)

You have already seen such a method: printf. For example, the calls

both call the same method, even though one call has two parameters and the other has three. The printf method is defined like this:

Here, the ellipsis ... is a part of the Java code. It denotes that the method can receive an arbitrary number of objects (in addition to the fmt parameter).

The printf method actually receives two parameters, the format string, and an Object[] array that holds all other parameters. (If the caller supplies integers or other primitive type values, autoboxing turns them into objects.) It now has the unenviable task of scanning the fmt string and matching up the ith format specifier with the value args[i].

In other words, for the implementor of printf, the Object... parameter type is exactly the same as Object[].

The compiler needs to transform each call to printf, bundling the parameters into an array and autoboxing as necessary:

You can define your own methods with variable parameters, and you can specify anytype for the parameters, even a primitive type. Here is a simple example: a function that computes the maximum of a variable number of values.

Simply call the function like this:

The compiler passes a new double[] { 3.1, 40.4, -5 } to the max function.

NOTE: It is legal to pass an array as the last parameter of a method with variable parameters.

For example:

Therefore, you can redefine an existing function whose last parameter is an array to a method with variable parameters, without breaking any existing code. For example, Message- Format.format was enhanced in this way in Java SE 5.0. If you like, you can even declare the main method as

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics