Why and How Does This Java Code Compile?

Viewed 152

The following code prints "String"

public class Riddle {

    public static void main(String[] args) {
        hello(null);
    }

    public static void hello(Object o) {
        System.out.println("Object");
    }


    public static void hello(String s) {
        System.out.println("String");
    }

}

Why does that code compile? Isn't null ambiguous?

For example, the following code will NOT compile because of an ambiguous signature.

public class Riddle {

    public static void main(String[] args) {
        hello(null);
    }

    public static void hello(Object o) {
        System.out.println("Object");
    }

    public static void hello(Integer o) {
        System.out.println("Integer");
    }

    public static void hello(String s) {
        System.out.println("String");
    }

}

Can someone please explain why the first example can compile without having ambiguous errors?

2 Answers
Related