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.


Correct Option: A
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

Find more quizzes: