Java Reference
In-Depth Information
Display 5.16
Comparing Parameters of a Class Type and a Primitive Type (part 2 of 2)
15 int aNumber = 42;
16 System.out.println("Value of aNumber before call to method:"
17 + aNumber);
18 object1.tryToMakeEqual(aNumber);
19 System.out.println("Value of aNumber after call to method:"
20 + aNumber);
21 }
22 }
Sample Dialogue
Value of object2 before call to method:
John Crichton 2
Value of object2 after call to method:
Scorpius 1
Value of aNumber before call to method: 42
Value of aNumber after call to method: 42
An argument of a class type
can change.
An argument of a primitive
type cannot change.
PITFALL: Use of = and == with Variables of a Class Type
You have already seen that the assignment operator used with variables of a class type
produces two variables that name the same object, which is very different from how
assignment behaves with variables of a primitive type.
The test for equality using == with variables of a class type also behaves in what
may seem like a peculiar way. The operator == does not check that the objects have
the same values for their instance variables. It merely checks for equality of memory
addresses, so two objects in two different locations in memory would test as being
“not equal” when compared using == , even if their instance variables contain equiva-
lent data. For example, consider the following code. (The class ToyClass2 is defi ned
in Display 5.17 .)
== with
variables of
a class type
ToyClass2 variable1 = new ToyClass2("Chiana", 3),
variable2 = new ToyClass2("Chiana", 3);
if (variable1 == variable2)
System.out.println("Equal using ==");
else
System.out.println("Not equal using ==");
This code will produce the output
Not equal using ==
(continued)
 
 
Search WWH ::




Custom Search