asked 129k views
1 vote
Analyze the following code.

public class Test {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
System.out.println("max(int, double) is invoked");
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
System.out.println("max(double, int) is invoked");
if (num1 > num2)
return num1;
else
return num2;
}
}
(a) The program cannot compile because you cannot have the print statement in a non-void method
(b) The program cannot compile because the compiler cannot determine which max method should be invoked
(c) The program runs and prints 2 followed by "max(int, double)" is invoke
(d) The program runs and prints 2 followed by "max(double, int)" is invoked
(e) The program runs and prints "max(int, double) is invoked" followed by 2.

1 Answer

5 votes

Final answer:

The correct answer is (e): The program compiles successfully, and when the main method invokes the 'max' method, it runs the version max(int, double) because Java converts the second integer argument to a double, printing "max(int, double) is invoked" followed by 2.

Step-by-step explanation:

The question asks to analyze a given Java code to test method overloading and determine the outcome when the main method invokes the max method. The program has two overloaded versions of the max method: one that takes an int and a double as arguments, and another that takes a double and an int.

When the main method calls max(1, 2), the first parameter is an int and the second is also an int, which means that Java will automatically promote the second argument to a double so it can match the first overloaded method signature, max(int, double). Therefore, the correct answer is (e): The program runs and prints "max(int, double) is invoked" followed by 2.

answered
User Sir Athos
by
9.2k points