Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and How Does This Java Code Compile? [duplicate]

Tags:

java

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?

like image 854
Jonathan Beaudoin Avatar asked Mar 23 '16 23:03

Jonathan Beaudoin


People also ask

Why do we compile Java code?

The result is machine code which is then fed to the memory and is executed. Java code needs to be compiled twice in order to be executed: Java programs need to be compiled to bytecode. When the bytecode is run, it needs to be converted to machine code.

How do you prevent duplicates in Java?

To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.

What is a duplicate class in Java?

The "duplicate class" error can also occur when the class is named the same with the same package naming hierarchy, even if one of the classes exists in a directory structure with directory names different than the package names.

How do you fix a compilation error in Java?

If the brackets don't all match up, the result is a compile time error. The fix to this compile error is to add a leading round bracket after the println to make the error go away: int x = 10; System.


1 Answers

In the second case doesn't compile as the compiler can't decide between the method that takes an Integer and the method that takes a String, where as in case of first the compiler can figure it out.

Reference : http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2

like image 141
Rishi Avatar answered Nov 04 '22 14:11

Rishi