Java Reference
In-Depth Information
Objects vs. References
Do not confuse a reference with the object that it refers to. They are two different enti-
ties. The reference is a variable that has a name and can be used to access the contents
of an object. A reference can be assigned to another reference, passed to a method, or
returned from a method. All references are the same size, no matter what their type is.
A reference is most likely 32 bits, but their actual size depends on your JVM.
An object sits on the heap and does not have a name. Therefore, you have no way to
access an object except through a reference. Objects come in all different shapes and
sizes and consume varying amounts of memory. An object cannot be assigned to another
object, nor can an object be passed to a method or returned from a method. It is the
object that gets garbage collected, not its reference.
The Heap
A Reference
An Object
name
A reference may or may
not be created on the heap.
All references are the same
size, no matter what their
data type is, and are accessed
by their variable name.
Objects are always on the heap.
They have no name and can only be
accessed via a reference. Objects vary in
size depending on their class definition.
Realizing the difference between a reference and an object goes a long way toward
understanding garbage collection, call by value, the new operator, and many other facets
of the Java language.
Consider the following program that instantiates two GregorianCalendar objects and
assigns them to various references. Study the code and see if you can determine when each
of the two objects either goes out of scope or all references to it are lost.
1. import java.util.GregorianCalendar;
2.
3. public class GCDemo {
4. public static void main(String [] args) {
5. GregorianCalendar christmas, newyears;
Search WWH ::




Custom Search