Multiple choice java

What will the result for following code?

public class Yikes {
    public static void go(Long n) {System.out.println("Long ");}
    public static void go(Short n) {System.out.println("Short ");}
    public static void go(int n) {System.out.println("int ");}

    public static void main(String [] args) {
        short y = 6;
        long z = 7;
        go(y);
        go(z);
    }
}

  1. int Long

  2. Short Long

  3. Compilation fails.

  4. An exception is thrown at runtime.

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

To solve this question, the user needs to know about method overloading, widening, and boxing/unboxing conversions in Java.

Each option can be evaluated as follows:

Option A: int Long

  • The first call to go() passes in a short argument. Since there is no exact match for a short parameter, the short value is widened to an int. Thus, the first call to go() invokes the go(int n) method and the output is "int ".
  • The second call to go() passes in a long argument, which matches the go(Long n) method. Thus, the second call to go() invokes the go(Long n) method and the output is "Long ".
  • Therefore, the output of the program is "int Long".

Option B: Short Long

  • The first call to go() passes in a short argument, which matches the go(Short n) method. Thus, the first call to go() invokes the go(Short n) method and the output is "Short ".
  • The second call to go() passes in a long argument, which matches the go(Long n) method. Thus, the second call to go() invokes the go(Long n) method and the output is "Long ".
  • Therefore, the output of the program is "Short Long".

Option C: Compilation fails.

  • There are no compilation errors in the code. The program will compile and run without errors.
  • Therefore, option C is incorrect.

Option D: An exception is thrown at runtime.

  • There are no exceptions thrown in the code. The program will execute without throwing any exceptions.
  • Therefore, option D is incorrect.

Therefore, the correct answer is:

The Answer is: A. int Long

AI explanation

Java overload resolution prefers widening primitive conversions over autoboxing. For go(y) where y is short: no go(short) overload exists, but short widens directly to int, so go(int) is chosen (widening beats boxing to Short) — printing 'int '. For go(z) where z is long: long cannot widen to int (that would be narrowing) and there's no go(long) overload, so the compiler falls back to autoboxing, wrapping z as a Long to match go(Long) — printing 'Long '. Combined output is 'int Long', matching the marked answer. It doesn't fail to compile (both calls resolve unambiguously) and no exception occurs, ruling out the other two options.