Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type on null as a method argument?

Tags:

java

So here it is this example

public static void main(String[] args) {        
    new Stuff(null);
    new Stuff("a");
    new Stuff(1);           
}

and class Stuff is defined as follow

public class Stuff {    
       Stuff(Object o){
           System.out.println("object");        
       }

       Stuff(String s){
           System.out.println("string");        
       }

}

The output is

string
string
object

How does Java tell the null is a String? If I change Stuff to

public class Stuff {    

       Stuff(String s){
           System.out.println("string");        
       }

       Stuff(Integer o){
           System.out.println("Integer");           
       }

}

I get compilation error for Stuff(null):

The constructore Stuff(String) is ambigous. 

Again, why does Java "decide" null is a String?

like image 939
Paolo Avatar asked Feb 16 '14 11:02

Paolo


People also ask

What is the type of null in Java?

In Java, null is a literal, a special constant you can point to whenever you wish to point to the absence of a value. It is neither an object nor a type, which is a common misconception newcomers to the Java language have to grapple with.

Can we pass null as argument in 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 pass null to a method?

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.

What is a null argument Java?

The Null object is a special instance of a class which represents missing value. If some method expects an object as a parameter, you can always pass the Null object representation without worry it will cause an unexpected exception at the runtime.


1 Answers

  • The compiler first lists all applicable methods. In your case, both are applicable.
  • It then tries to find a method which is more specific than the other(s).
  • In your first example, String is a subclass of Object and is therefore more specific.
  • In your second example, both methods are applicable (String and Integer) but neither is more specific than the other (String is not a subclass of Integer which is not a subclass of String). So there is an ambiguity, hence the compiler error.

The full algorithm to determine which method should be chosen is defined in the JLS.

like image 54
assylias Avatar answered Oct 01 '22 14:10

assylias