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"); }
}- A. It fails to compile: you cannot have both a fixed-arity and varargs overload with compatible parameter types
- B. Calling f(1, 2) is ambiguous and fails to compile
- C. Calling f(1, 2) always picks the varargs version because it's more general
- 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
- Which statement is correct? java interface Shape { double area(); } abstract class AbstractShape implements Shape { public abstract double…
- What is printed? java class Stack<T> { private List<T> items = new ArrayList<>(); void push(T item) { items.add(item); } T pop() { return…
- Which statement is correct? java class Event { protected void log() { System.out.print("Event.log"); } } class ClickEvent extends Event {…
- What is printed? java class Base { public Base() { System.out.print("Base "); } public Base(Base other) { System.out.print("BaseCopy "); }…
- What is printed? cpp struct Base { virtual void run() { step1(); step2(); } virtual void step1() { cout << "B1 "; } virtual void step2() {…
- What is printed? java class Account { protected double balance; Account(double b) { balance = b; } void transfer(Account to, double amt) {…