I am going through “The Java Handbook” by Patrick Naughton.
Book says: When you declare the type of a variable to be a class, it has a default value of null which is a reference of type Object, and is thus type-compatible with all the other classes. The null object has no value; it is distinct from the integer 0, just like boolean’s false.
I cannot understand/confuse the highlighted part, does it say that null is a variable of type Object?
Page no: 107
para: 5
It’s a reference value, not a reference variable. Any variable that is a reference type can have the value null. (In Java, all variables are either reference types or primitive types (
int,char,float, etc.). (Well, there are also type variables when you start to talk about generics.)Here’s the relevant part of the Java Language Specification:
EDIT To address your comment: I think the language in "The Java Handbook" is a little off the mark. The value
nullis not a reference of typeObject; it is a reference of the null type. The key point from the spec is that "the null reference can always undergo a widening reference conversion to any reference type". This is, in a sense, exactly the opposite ofObject. AnObjectreference is the widest type of reference; thenulltype is (to also speak a little loosely) the narrowest. In particular, assigning a reference of typeObjectto a variable of any other reference type is a narrowing conversion that requires an explicit cast (and can raise aClassCastException). Assigning thenullreference to a variable of any reference type never requires a cast and cannot raise an exception.Note that no named reference type can have the behavior of the null type. There really is no "narrowest type" since the (named) type system in Java does not not have such a thing. It is impossible to define a reference type that is assignable to, say, both a
Stringvariable and aDoublevariable. Only the null type has that property. The normal rules for reference type conversion do not allow this, which is why it has a separate rule in the Java Language Specification.