1Z0-819 · Question #162
What is the result of compiling and running the following code? public class Overload { static void print(int..., a2) { System.out.print("int...."); } static void print(long a, long b) {…
The correct answer is C. Prints long, long. Calling print(a, b) with an int and a long triggers Java's overload resolution rules, which select the print(long, long) method because widening primitive conversion (int → long) is preferred over both autoboxing and varargs. The first parameter a is widened from int to long…
Question
Options
- ADoes not compile
- BPrints int
- CPrints long, long
- DPrints Integer, Integer
- EThrows an exception
- FNone of these
How the community answered
(30 responses)- A10% (3)
- B3% (1)
- C80% (24)
- D3% (1)
- F3% (1)
Explanation
Calling print(a, b) with an int and a long triggers Java's overload resolution rules, which select the print(long, long) method because widening primitive conversion (int → long) is preferred over both autoboxing and varargs. The first parameter a is widened from int to long, producing an exact match for print(long a, long b).
Why the distractors are wrong:
- A - Assuming the
int...signature is valid (i.e.,int... a2), the code compiles fine; the unusual formatting is a red herring. - B - The
int...varargs overload is deprioritized because Java always prefers a fixed-arity method over varargs when any match is found. - D -
Integer, Integerrequires autoboxing, which ranks below widening in resolution; Java picks widening first. - E/F - No runtime exception occurs; this is purely a compile-time resolution decision.
Memory tip: Java overload resolution follows a strict priority ladder - Exact → Widen → Box → Varargs. Think "Wide before Box, Box before Dots." Widening an int to long costs nothing at runtime, so Java favors it over boxing or varargs every time.
Topics
Community Discussion
No community discussion yet for this question.