Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java null corresponds to Double

Tags:

java

I have no idea how to ask this question or what title to use. I hope i do not violate any rules. Anyway, can someone explain to me the following behavior? I have this code:

X x = new X();
x.dosmth(null);

static class X{
        void dosmth(Object obj) { System.out.println("X:Object"); }
        void dosmth(Double obj) { System.out.println("X:Double"); }
        void dosmth(int obj) { System.out.println("X:int"); }
        void dosmth(double obj) { System.out.println("X:double"); }
        void dosmth(char obj) { System.out.println("X:char"); }
        void dosmth(byte obj) { System.out.println("X:byte"); }
}

What i get is this:

X:Double

Why it ignores completely the line

void dosmth(Object obj) { System.out.println("X:Object"); }

And why null corresponds to Double and not Object?

In addition, if i add this line:

void dosmth(Integer obj) {System.out.println("X:Integer"); }

i get the following error:

both method dosmth(java.lang.Integer) and method dosmth(java.lang.Double) match
like image 227
Angelo Uknown Avatar asked May 10 '26 09:05

Angelo Uknown


1 Answers

When choosing an overloaded method, null can correspond to any reference type. When there are two candidates - Object and Double in your case - the most specific one is chosen - Double (Double is more specific than Object since it's a sub-class of Object).

When you introduce void dosmth(Integer obj), there are three candidates - Object, Double and Integer - but since neither Double nor Integer is more specific than the other - the compiler can't choose between then and you get an error.

As mentioned by FINDarkside, if you which a specific method to be chosen, you can cast the null to the desired type.

For example, this will force the compiler to choose void dosmth(Object obj) :

x.dosmth((Object)null);
like image 186
Eran Avatar answered May 12 '26 23:05

Eran