Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null value in method parameter [duplicate]

I have the following code

import java.util.List;

public class Sample {

    public static void main(String[] args) {
      test(null);
    }

    static void test(List<Object> a){
        System.out.println("List of Object");
    }
    static void test(Object a){
        System.out.println("Object");
    }
}

and I got following output in console

List of Object

Why doesn't this call test(Object a)? Can you some one explain how it took "List as" null?

like image 875
Kannan Thangadurai Avatar asked May 08 '15 15:05

Kannan Thangadurai


People also ask

Can we pass null to a method as parameter?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter.

What happens if we pass null in a method in Java?

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.

Can you return null in a method?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.


2 Answers

In a nutshell, the most specific method among the overloads is chosen.

In this case the most specific method is the one that takes List<Object> since it's a subtype of Object.

The exact algorithm Java uses to pick overloaded methods is quite complex. See Java Language Specification section 15.12.2.5 for details.

like image 60
aioobe Avatar answered Nov 10 '22 14:11

aioobe


Always specific first, in cases like that. If you change List to String, it will print the same thing. Every class is child of Object, so if it have to overload, will be to the more specific class.

like image 44
Raphael Amoedo Avatar answered Nov 10 '22 14:11

Raphael Amoedo