Tricky Java question

What is the output of the below program?

public class ObjectOrString {

public static void main(String[] args) {

public static void method(Object o) {
   System.out.println("Object used");

public static void method(String s) {
  System.out.println("String used");

My first guess was that method with String parameter will be called and I was right, I don’t know, somehow I couldn’t think about null as a Object. But as a tricky question it would be too simple just to say that second method will called and that’s it.
After some additional reading I found proper explanation for it, it’s a quite a lot to read Method Invocation Expressions , in short:
In case of overloading, compiler picks the most specific function. Obviously String class is more specific that Object class.

I’ve never encounter this kind of ‘problem’ when coding, but I can imagine some surprised developers tracing their code.

Leave a Reply