nerdexam
Oracle

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…

Java Object-Oriented Approach

Question

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) { System.out.print("long...."); } static void print(Integer a1, Integer a2) { System.out.print("Integer, Integer"); } public static void main(String[] args) { int a = 1; long b = 1L; print(a, b); } }

Options

  • ADoes not compile
  • BPrints int
  • CPrints long, long
  • DPrints Integer, Integer
  • EThrows an exception
  • FNone of these

How the community answered

(30 responses)
  • A
    10% (3)
  • B
    3% (1)
  • C
    80% (24)
  • D
    3% (1)
  • F
    3% (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 (intlong) 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, Integer requires 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

#Method Overloading#Type Widening#Method Resolution#Primitive Conversion

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice