nerdexam
Oracle

1Z0-829 · Question #23

Given: public class Test { public void sum(int a, int b) { System.out.print("A"); } public void sum(int a, float b) { System.out.print("B"); } public void sum(float a, float b) {…

The correct answer is C. B A D. There is an error in this exam question's stated answer. Based on the Java Language Specification, the correct output is D A D (choice B), not B A D. Why each call resolves as it does: t.sum(10, 24) → A: Both arguments are int literals - exact match for sum(int a, int b)…

Java Object-Oriented Approach

Question

Given: public class Test { public void sum(int a, int b) { System.out.print("A"); } public void sum(int a, float b) { System.out.print("B"); } public void sum(float a, float b) { System.out.print("C"); } public void sum(double... a) { System.out.print("D"); } public static void main(String[] args) { Test t = new Test(); t.sum(10,15.25); t.sum(10, 24); t.sum(10.25,10.25); } } What is the result?

Options

  • AB A C
  • BD A D
  • CB A D
  • DD D D

How the community answered

(57 responses)
  • A
    9% (5)
  • B
    23% (13)
  • C
    63% (36)
  • D
    5% (3)

Explanation

There is an error in this exam question's stated answer. Based on the Java Language Specification, the correct output is D A D (choice B), not B A D.

Why each call resolves as it does:

  • t.sum(10, 24)A: Both arguments are int literals - exact match for sum(int a, int b).
  • t.sum(10.25, 10.25)D: 10.25 is a double literal. None of the first three overloads accept double without narrowing (which Java forbids implicitly), so Java falls back to the varargs overload sum(double... a).
  • t.sum(10, 15.25)D, not B: 15.25 without an f suffix is a double literal in Java. sum(int a, float b) would require a narrowing conversion (doublefloat), which Java does not perform implicitly. Java therefore falls back to sum(double... a).

Why the distractors are wrong:

  • A (B A C): sum(10.25, 10.25) cannot match sum(float a, float b) because doublefloat is a narrowing conversion.
  • C (B A D): sum(int a, float b) is never called - 15.25 is a double, not a float.
  • D (D D D): sum(10, 24) is an exact match for sum(int, int), so varargs is never reached.

Memory tip: In Java, any floating-point literal without an f/F suffix is a double. When no overload can accept the arguments without narrowing, Java escalates to varargs (double...) - it never narrows implicitly.

Topics

#Method Overloading#Type Promotion#Varargs#Type Matching

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice