The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloading methods (null argument) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overloading methods (null argument)" Watch "Overloading methods (null argument)" New topic

Overloading methods (null argument)

Gosia Wittemann
Ranch Hand

Joined: Nov 02, 2007
Posts: 50
It's a question from JavaBelt exam:

What is the output of the following code?

01: public class A {
02: public static void test(Object a) {
03: System.out.println("Object");
04: }
05: public static void test(String a) {
06: System.out.println("String");
07: }
09: public static void main(String args[]) {
10: test(null);
11: }
12: }

The answers:
Compilation error
Runtime error

I though it should be an object, the right answer is a String, but I don't understand why.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
It's a case of the most specific applicable method being called, and String is more specific than Object.

An interesting experiment would be to add another method that takes some other class (e.g. a StringBuffer), and to answer the question for that class.
Sergey Petunin
Ranch Hand

Joined: Dec 16, 2007
Posts: 44
The method with the most concrete subclass is selected. String is a subclass of Object, and null can be cast to any class, so the String method is selected.
Serg Masow
Ranch Hand

Joined: Dec 17, 2007
Posts: 50
the compiler always choose the most specific method, which will be invoked. This blog linkdecribes very well the choose of the "most specific method"

SCJP 6.0 [95%] OCE EJBD 6.0 [93%]
Gosia Wittemann
Ranch Hand

Joined: Nov 02, 2007
Posts: 50
Thanks for your answers. Of course, I should have thought of it.

I tried it with a method with a StringBuffer type parameter and you get a:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method test(Object) is ambiguous for the type A

as expected.
I agree. Here's the link:
subject: Overloading methods (null argument)
It's not a secret anymore!