The answer is C because the code demonstrates the concept of method overloading and type
conversion in Java. Method overloading allows different methods to have the same name but
different parameters. Type conversion allows values of one data type to be assigned to another data
type, either automatically or explicitly. In the code, the class Test has four methods named sum, each
with different parameter types: int, float, and double. The main method creates an instance of Test
and calls the sum method with different arguments. The compiler will choose the most specific
method that matches the arguments, based on the following rules:
If there is an exact match between the argument types and the parameter types, that method is
chosen.
If there is no exact match, but there is a method with compatible parameter types, that method is
chosen. Compatible types are those that can be converted from one to another automatically, such
as int to long or float to double.
If there is more than one method with compatible parameter types, the most specific method is
chosen. The most specific method is the one whose parameter types are closest to the argument
types in terms of size or precision.
In the code, the following method calls are made:
test.sum(10, 10.5) -> This matches the sum(int a, float b) method exactly, so it is chosen. The result is
20.5, which is converted to int and printed as 20 (B).
test.sum(10) -> This does not match any method exactly, but it matches the sum(double a) method
with compatible types, as int can be converted to double automatically. The result is 10.0, which is
printed as 10 (A).
test.sum(10.5, 10) -> This does not match any method exactly, but it matches two methods with
compatible types: sum(float a, float b) and sum(double a, double b). The latter is more specific, as
double is closer to the argument types than float. The result is 20.5, which is printed as 20 (D).
Therefore, the output is B A D. Reference:
Oracle Certified Professional: Java SE 17 Developer
Java SE 17 Developer
OCP Oracle Certified Professional Java SE 17 Developer Study Guide
Method Overloading in Java
Type conversion in Java with Examples
Java Method Overloading with automatic type conversions