1Z0-830 practice question 6 of 25

Which of the following statements about overloaded methods with varargs is TRUE?

Full set: 116 questions
Answer options
A:

A. A varargs parameter can be of any primitive type.

B:

B. A varargs parameter must be the only parameter in the method signature.

C:

C. A method can be overloaded based solely on the presence or absence of a varargs parameter.

Correct answer
D:

D. The compiler throws an error if you call a varargs method with zero arguments.

Correct Answer:
C. C. A method can be overloaded based solely on the presence or absence of a varargs parameter.
Explanation

A method can be overloaded with both a fixed-arity version and a varargs version, for example, myMethod(int x) and myMethod(int... x). When such a method is called, the compiler uses overload resolution rules to pick the most specific version. A call with a single integer argument will match the fixed-arity method, while calls with zero or multiple integer arguments will match the varargs version. This demonstrates that overloading based on the presence of a varargs parameter is a valid and well-defined feature in Java.

Why Incorrect

A. A varargs parameter can be of any primitive or reference type, so this statement is also true, but C is more specific to the topic of overloading with varargs.
B. A varargs parameter must be the last parameter in the signature, but it does not have to be the only one.
D. Calling a varargs method with zero arguments is perfectly valid and results in an empty array being passed to the method.

References

1. Oracle, The Java™ Tutorials. "Passing Information to a Method or a Constructor", section on "Arbitrary Number of Arguments". It shows examples of varargs methods and how they are called.

2. Java® Language Specification, Java SE 17 Edition, §15.12.2.5. "Choosing the Most Specific Method". This section details how the compiler resolves ambiguity between applicable methods, including fixed-arity versus variable-arity methods, preferring the former when applicable.

3. Java® Language Specification, Java SE 17 Edition, §8.4.1. "Formal Parameters". This section defines the syntax for a variable arity parameter, stating it must be the last parameter in the list.

Scroll to Top