Java Daily, Quiz 5

Welcome to Java daily quiz 5 of Java daily quiz series, you can test yourself with this Java quiz. The answer and explanation are given at the end for your reference.
Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html.
Check out my YouTube channel at https://www.youtube.com/c/javaguides.

Quiz 5 - Consider the following program and predict the output:

public class Test {
    public void print(Integer i) {
        System.out.println("Integer");
    }

    public void print(int i) {
        System.out.println("int");
    }

    public void print(long i) {
        System.out.println("long");
    }

    public static void main(String args[]) {
        Test test = new Test();
        test.print(10);
    }
}
a) The program results in a compiler error (“ambiguous overload”).
b) long
c) Integer
d) int

Answer

d) int
Explanation:   For an integer literal, the JVM matches in the following order: int, long, Integer, int.... In other words, it first looks for an int type parameter; if it is not provided, then it looks for a long type; and so on. Here, a literal will match to int. So, the program prints int.

The automatic type promotion in java method overloading concept is very important for an interview. The following diagram summarizes the automatic type promotions for the method overloading:

Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html.
Check out my YouTube channel at https://www.youtube.com/c/javaguides.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments