9

Why does this output: "inside String argument method"? Isn't null "Object" type?

class A {
    void printVal(String obj) {
        System.out.println("inside String argument method");
    }

    void printVal(Object obj) {
        System.out.println("inside Object argument method");
    }

    public static void main(String[] args) {
        A a = new A();
        a.printVal(null);
    }
}
brainydexter
  • 19,826
  • 28
  • 77
  • 115
  • 1
    Wow crazy. I just tried adding a third `printVal` overload, `printVal(Integer obj)` to see what would happen. Now `a.printVal(null)` is a compiler error, due to ambiguity. Good question. – mgiuca Feb 06 '11 at 01:55

3 Answers3

8

The most specific matching method will be called. More information here:

Community
  • 1
  • 1
Gunslinger47
  • 7,001
  • 2
  • 21
  • 29
3

Yes, but null is also String type and all other types, so it selects the most specific method to call.

amara
  • 2,216
  • 2
  • 20
  • 28
1

More specifically, a null literal will call the String version, for the reasons outlined by the other answers.

On the other hand:

class A {
    void printVal(String obj) {
        System.out.println("inside String argument method");
    }

    void printVal(Object obj) {
        System.out.println("inside Object argument method");
    }

    public static void main(String[] args) {
        A a = new A();
        Object myObj = null;
        a.printVal(myObj);
    }
}

will print "inside Object argument method." As will settings the type for myObj to any type other than String.

Powerlord
  • 87,612
  • 17
  • 125
  • 175