Java Reference
In-Depth Information
example, might hold two double values to represent the x and y coordinates of
the points. The char[] and Point[] array types are aggregate types because
they hold a sequence of primitive char values or Point objects.
• Primitive types require between one and eight bytes of memory. When a primi‐
tive value is stored in a variable or passed to a method, the computer makes a
copy of the bytes that hold the value. Objects, on the other hand, may require
substantially more memory. Memory to store an object is dynamically allocated
on the heap when the object is created and this memory is automatically
“garbage collected” when the object is no longer needed.
a x
When an object is assigned to a variable or passed to a
method, the memory that represents the object is not copied.
Instead, only a reference to that memory is stored in the vari‐
able or passed to the method.
References are completely opaque in Java and the representation of a reference is an
implementation detail of the Java runtime. If you are a C programmer, however, you
can safely imagine a reference as a pointer or a memory address. Remember,
though, that Java programs cannot manipulate references in any way.
Unlike pointers in C and C++, references cannot be converted to or from integers,
and they cannot be incremented or decremented. C and C++ programmers should
also note that Java does not support the & address-of operator or the * and -> deref‐
erence operators.
Manipulating Objects and Reference Copies
The following code manipulates a primitive int value:
int x = 42 ;
int y = x ;
After these lines execute, the variable y contains a copy of the value held in the vari‐
able x . Inside the Java VM, there are two independent copies of the 32-bit
integer 42.
Now think about what happens if we run the same basic code but use a reference
type instead of a primitive type:
Point p = new Point ( 1.0 , 2.0 );
Point q = p ;
After this code runs, the variable q holds a copy of the reference held in the variable
p . There is still only one copy of the Point object in the VM, but there are now two
copies of the reference to that object. This has some important implications. Sup‐
pose the two previous lines of code are followed by this code:
Search WWH ::

Custom Search