-1

How javac (java compiler) finds the errors in respect to ambiguity and generates errors in compile time itself ?

how the compiler finds that we are passing a null value before execution

public class Ambiguity {

 public static void main(String[] args) {
    Ambiguity test = new Ambiguity();
    test.overloadedMethod(null);               

}

void overloadedMethod(IOException e) {
    System.out.println("1");
}

void overloadedMethod(FileNotFoundException e) {
    System.out.println("2");
}

void overloadedMethod(Exception e) {
    System.out.println("3");
}

void overloadedMethod(ArithmeticException e) {
    System.out.println("4");
}

}
Sethu MJ
  • 49
  • 3
  • What do you mean by "how"? Do you want to know how the compiler is implemented? You can view the source code of OpenJDK's compiler on their GitHub repo, but I'm not sure if that's what you want. – Sweeper Sep 21 '22 at 10:01

1 Answers1

3

The point isn't that the compiler knows you're passing null; the point is that when you write a literal null in your code, the compiler doesn't know what the type of that null is, so it doesn't know which overload to call.

This, for example, would compile just fine:

    FileNotFoundException e = null;
    test.overloadedMethod(e);

You can also use an explicit cast to indicate which type you intended:

    test.overloadedMethod((FileNotFoundException) null);

Keep in mind that overloading is resolved at compile time. So if you're calling test.overloadedMethod(e) where e is statically of type Exception, it will always call overloadedMethod(Exception) even if e is a FileNotFoundException at runtime.

Thomas
  • 174,939
  • 50
  • 355
  • 478