Java Reference
In-Depth Information
You can think of the
jack
variable as a remote controller for a
Human
instance in memory. You can refer to the
Human
instance in memory using the
jack
variable. I will discuss how to use a reference variable in the next section.
You can also combine the above two statements into one.
Human jack = new Human();
The null Reference Type
Every class in Java defines a new reference type. Java has a special reference type called null type. It has no name.
Therefore, you cannot define a variable of the null reference type. The null reference type has only one value defined
by Java, which is the
null
literal. It is simply
null
. The null reference type is assignment compatible with any other
reference type. That is, you can assign a
null
value to a variable of any reference type. Practically, a
null
value stored
in a reference type variable means that the reference variable is referring to no object. You can think of storing a
null
to a reference variable as a string with no balloon attached to it, where balloon is a valid object and string is a
reference variable. For example, you can write code like
// Assign null value to john
Human john = null; // john is not referring to any object
john = new Human(); // Now, john is referring to a valid Human object
You can use a
null
literal with comparison operators to check for equality and inequality.
if (john == null) {
// john is referring to null. Cannot use john for anything
}
if (john != null) {
// Do something with john
}
Note that
null
is a literal of null type. Java does not let you mix reference types and primitive types. You cannot
assign
null
to a primitive type variable. The following assignment statement will generate a compilation time error:
// A compile-time error. A reference type value, null, cannot be assigned to
// a primitive type variable num
int num = null;
Because
null
(or any reference type value) cannot be assigned to a primitive type variable, Java compiler does
not allow you to compare a primitive value to a
null
value. The following comparison will generate a compilation
time error. In other words, you can compare a reference type with reference types, and a primitive type with
primitive types.
int num = 0;
// A compile-time error. Cannot compare a primitive type to a reference type
if (num == null) {
}