ProgrammingHardWipro · Cognizant pattern

Which statement about overload resolution with varargs is correct?

Which statement about overload resolution with varargs is correct?
class A {
    void f(int a, int b) { System.out.print("fixed"); }
    void f(int... nums) { System.out.print("varargs"); }
}
  1. A. It fails to compile: you cannot have both a fixed-arity and varargs overload with compatible parameter types
  2. B. Calling f(1, 2) is ambiguous and fails to compile
  3. C. Calling f(1, 2) always picks the varargs version because it's more general
  4. D. Calling f(1, 2) picks the fixed-arity overload f(int,int); varargs is only used when no fixed-arity overload matches (e.g. f(1,2,3) or f())

Correct answer: D. Calling f(1, 2) picks the fixed-arity overload f(int,int); varargs is only used when no fixed-arity overload matches (e.g. f(1,2,3) or f())

Java's overload resolution always prefers a non-varargs (fixed-arity) match over a varargs match, trying varargs only as a last resort. f(1,2) matches f(int,int) exactly, so 'fixed' is chosen; only calls like f(1,2,3) or f() would fall through to f(int...).

More OOP with C++ and Java questions

Exams that ask this topic