Java Reference
In-Depth Information
The variables refer to the fields a.name and a.price . Of course, p.name and p.price refer to the fields of the
argument to equals ( b , in the example). In effect, the return statement becomes this:
return a.name.equals(b.name) && (a.price == b.price);
Now, suppose we have these statements:
Part a = new Part("Air Filter", 8.75);
Part b = new Part("Air Filter", 8.75);
(a == b) is false (since a and b hold different addresses), but a.equals(b) is true (since the contents of the
objects they point to are the same).
2.9 The null Pointer
An object variable is declared as in the following example:
Part p;
Initially, it is undefined (just like variables of the primitive types). The most common way to give p a value is to
create a Part object and store its address in p using the new operator, like this:
p = new Part("Air Filter", 8.75);
Java also provides a special pointer value, denoted by null , which can be assigned to any object variable. We
could write the following to assign null to the Part variable, p :
Part p = null;
In effect, this says that p has a defined value, but it does not point to anything. If p has the value null , it is an error
to attempt to reference an object pointed to by p . Put another way, if p is null , it makes no sense to talk about p.name
or p.price since p is not pointing to anything.
If two object variables p and q are both null , we can compare them with == , and the result will be true . On the
other hand, if p points to some object and q is null , then, as expected, the comparison is false .
Null pointers are useful when we need to initialize a list of object variables. We also use them when we are
creating data structures such as linked lists or binary trees and we need a special value to indicate the end of a list. We
will see how to use null pointers in the next chapter.
2.10 Passing an Object as an Argument
An object variable holds an address—the address of an actual object. When we use an object variable as an argument
to a method, it's an address that is passed to the method. Since arguments in Java are passed “by value,” a temporary
location containing the value of the variable is what is actually passed. In Section 2.6.1, we met the static method
printPart in the class Part for printing a part. Here it is:
public static void printPart(Part p) {
System.out.printf("\nName of part: %s\n", p.name);
System.out.printf("Price: $%3.2f\n", p.price);
}
 
Search WWH ::




Custom Search