Given: class Alien { String invade(short ships) { return "a few"; } String invade(short... ships) { return "many"; } } class Defender { public static void main(String [] args) { System.out.println(new Alien().invade(7)); } } What is the result?

  1. many

  2. a few

  3. Compilation fails

  4. The output is not predictable

  5. An exception is thrown at runtime


Correct Option: C

AI Explanation

To answer this question, we need to understand method overloading and method invocation in Java.

In the given code, there are two methods in the Alien class with the same name but different parameters: 1) String invade(short ships) 2) String invade(short... ships)

The first method takes a single short parameter, while the second method takes a variable number of short parameters.

In the Defender class, the main method creates a new instance of the Alien class and invokes the invade method with an argument of 7.

Since 7 is an integer literal, it is implicitly converted to a short before being passed as an argument to the invade method.

Now, the Java compiler tries to find the most specific method to invoke based on the argument passed. In this case, both methods can accept a short argument, so the method with a single short parameter is a more specific match.

However, when there are multiple methods with the same name and same specificity of match, the Java compiler gives priority to methods without varargs. In this case, the method with varargs is considered less specific.

Hence, the compiler fails because it cannot determine which invade method to invoke, resulting in a compilation error.

Therefore, the correct answer is option C) Compilation fails.

Find more quizzes: