0

Why null goes to method Which Accepts The String

class Test {
    public static void test(String s)
    {
        System.out.println("In String");
    }
    public static void test(Object o) {
        System.out.println("In Object");
    }

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

I expect The Result To be In Object as Strings Are Usually Passed in("")

markspace
  • 10,621
  • 3
  • 25
  • 39

2 Answers2

1

Java will always try to call the the most specific version of a method. This is part of the Java Language Specification.

Check this answer for more details and a link to the JLS: https://stackoverflow.com/a/5229890/1426538

Asotos
  • 995
  • 11
  • 14
0

See JLS § 15.12.2.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25