And we invoke the method as : test(null) : from another class, the
method with the String parameter is executed. Any particular reason
for this?
JLS 3 § 15.12.2, your goto resource for pretty much any question about
why a method invocation is doing what it is doing.
A brief overview of what happens in this particular case:
First, the compiler selects all the possible methods that the invocation
could match based on name and arity (in the absence of varargs, which is
a bit trickier) (§ 15.12.1 and § 15.12.2.1 goes into this in more detail
if you really want to know, but it's pretty intuitive). In your case,
this is both of the test methods.
After that, the compiler looks at types to figure stuff out. If you
regress to pre-1.5 functionality, the subtyping is pretty simple. The
compiler is basically asking "how well do each of these methods match
what the user is trying?"; all expressions have types (the assignment of
types is fairly straightforward, see most of § 15 if you really want to
know in full gory detail), so it's trying to match the types to the
types that the method supports--identifying matching methods by subtyping.
All types have supertypes: it is pretty much the same relation between
classes and superclasses, so all reference types are subtypes of Object.
The null type's supertypes are all reference types other than null.
In your case, you have an expression whose type is the null type. Since
null is a subtype of String and Object, this phase of the search selects
both test methods. In the next phase, we need to choose between them.
The powers that be decided that the most intuitive thing to do is to
select the "most specific" method, where "most specific" has particular
meaning. In the absence of generics, if method A is more specific than
method B, than the arguments of A have declared types that are subtypes
of method B's arguments. Under this definition, test(String) is more
specific than test(Object), so it is the one chosen.
Note that if you also had a test(Set) method, there would be no most
specific method, and the compiler would complain at you as a result.