Java Reference
In-Depth Information
System . out . println ( p . x ); // Print out the x coordinate of p: 1.0
q . x = 13.0 ; // Now change the X coordinate of q
System . out . println ( p . x ); // Print out p.x again; this time it is 13.0
Because the variables p and q hold references to the same object, either variable can
be used to make changes to the object, and those changes are visible through the
other variable as well. As arrays are a kind of object then the same thing happens
with arrays, as illustrated by the following code:
// greet holds an array reference
char [] greet = { 'h' , 'e' , 'l' , 'l' , 'o' };
char [] cuss = greet ; // cuss holds the same reference
cuss [ 4 ] = '!' ; // Use reference to change an element
System . out . println ( greet ); // Prints "hell!"
A similar difference in behavior between primitive types and reference types occurs
when arguments are passed to methods. Consider the following method:
void changePrimitive ( int x ) {
while ( x > 0 ) {
System . out . println ( x --);
When this method is invoked, the method is given a copy of the argument used to
invoke the method in the parameter x . The code in the method uses x as a loop
counter and decrements it to zero. Because x is a primitive type, the method has its
own private copy of this value, so this is a perfectly reasonable thing to do.
On the other hand, consider what happens if we modify the method so that the
parameter is a reference type:
void changeReference ( Point p ) {
while ( p . x > 0 ) {
System . out . println ( p . x --);
When this method is invoked, it is passed a private copy of a reference to a Point
object and can use this reference to change the Point object. For example, consider
the following:
Point q = new Point ( 3.0 , 4.5 ); // A point with an x coordinate of 3
changeReference ( q ); // Prints 3,2,1 and modifies the Point
System . out . println ( q . x ); // The x coordinate of q is now 0!
When the changeReference() method is invoked, it is passed a copy of the refer‐
ence held in variable q . Now both the variable q and the method parameter p hold
references to the same object. The method can use its reference to change the con‐
tents of the object. Note, however, that it cannot change the contents of the variable
q . In other words, the method can change the Point object beyond recognition, but
it cannot change the fact that the variable q refers to that object.
Search WWH ::

Custom Search