Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null to the method preferring String, not Object

I am facing an issue in my program and I made it clear with a small code snippet below. Can anyone explain why this is happening?

class ObjectnullTest {

    public void printToOut(String string) {

        System.out.println("I am null string");
    }


    public void printToOut(Object object)

        System.out.println("I am  null object");
    }



class Test {

    public static void main(String args[]) {

        ObjectnullTest a = new ObjectnullTest();
        a.printToOut(null);

    }
}

This always prints I am null string .

I want to know the reason so that I can modify the code .

like image 885
Suresh Atta Avatar asked Feb 23 '13 23:02

Suresh Atta


People also ask

Can you pass null as a string?

Null Type. In Java, null is neither an Object nor a type. It is a special value that we can assign to any reference type variable. We can cast null into any type in which we want, such as string, int, double, etc.

Can we pass null as string argument in Java?

You cannot pass the null value as a parameter to a Java scalar type method; Java scalar types are always non-nullable. However, Java object types can accept null values.

Can we pass null to the method?

When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value. For example see the below scenario which we follow generally while coding.

Can we pass null as object in Java?

No, 'null' is a value. In java you are passing arguments to function as reference (except basic types), which value (of this reference) 'points' to object. In this case value of reference points to nothing.


1 Answers

It's because In case of method Overloading

The most specific method is choosen at compile time.

As 'java.lang.String' is a more specific type than 'java.lang.Object'. In your case the method which takes 'String' as a parameter is choosen.

Its clearly documented in JLS:

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run-time to perform the method dispatch.

like image 63
PermGenError Avatar answered Oct 17 '22 09:10

PermGenError