Variable-Length Argument Lists
Paul Ngugi
Posted on May 28, 2024
A variable number of arguments of the same type can be passed to a method and treated as an array. You can pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows:
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.
Java treats a variable-length parameter as an array. You can pass an array or a variable number of arguments to a variable-length parameter. When invoking a method with a variable number of arguments, Java creates an array and passes the arguments to it. The program below contains a method that prints the maximum value in a list of an unspecified number of values.
Line 6 invokes the printMax method with a variable-length argument list passed to the array numbers. If no arguments are passed, the length of the array is 0 (line 14). Line 7 invokes the printMax method with an array.
Posted on May 28, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.