public void m1(Integer f) {
...
}
public void m1(Float f) {
...
}
public void main() {
m1(null); // error: the method m1(Integer) is ambiguous for the type Main
m1((Integer) null); // success
}
Given the above example, we can admit in some ways that null is typed. So why do the following lines print true? Sure o1 and o2 both have no value (i.e. null), but they aren’t from the same type (Integer vs Float). I firstly thought false would have been printed.
Integer i = null;
Object o1 = (Object) i;
Float f = null;
Object o2 = (Object) f;
System.out.println(o1 == o2); // prints true
// in short:
System.out.println(((Object) ((Integer) null)) == ((Object) ((Float) null))); // prints true
All
nullvalues are untyped and are equal. You can pass it to different reference types but it makes no difference for comparison purposes.It is not the
nullvalue which is typed but the reference to the null which can be typed.A common question is what happens here
The compiler sees the type of
aas anAso the static method is called. But the value referenced isnulland untyped.The only operations you can perform with
nullwithout causing a NullPointerException is to assign or pass it without examining it or comparing it with another reference.BTW
In short: The compiler will select a method based on the type of the reference, at runtime the execution is based on the class of the object referenced. At runtime
nullis treated as any type or no type or you get a NullPointerException if you try to dereference it.