Java Reference
In-Depth Information
collection does all of this for the programmer, simplifying the writing of programs and librar-
ies and making the programs themselves more robust.
Garbage Collection and References
Even though garbage collection is invisible to the programmer, there are lots of effects of
garbage collection that leave their marks all over the language. The most obvious of these are
the lack of pointers in Java and the use of references everywhere.
In languages such as C or C++, there are objects (or structures) and there are pointers to those
objects. The C notion of a pointer is really an address in memory; the value of a pointer is a
real place (or as real as virtual memory allows it to be) that is the location in the store where
your data is located. If you have an object foo with a field bar , you get the value of the
field by . But if fooptr is a pointer to foo , you get the value held in field bar with
fooptr->bar . It's like dealing with the White Knight in Through the Looking Glass —you
need to be careful about whether you are talking about the thing or what the thing is called.
In the Java language, there is only a single way to access an object, and it is a reference. A
reference is like a pointer in C or C++, in that it is an indirect mechanism allowing access to
objects in memory. But it is unlike a pointer in every other way. You can't access the refer-
ence itself, and in particular you can't get a reference to a reference in the way you can get a
pointer to a pointer. You can't do arithmetic with a reference; adding 1 to a pointer in C gives
you another pointer, but adding 1 to a Java reference either adds one to the object referenced
or gives you a compilation error. All you can do with a reference (other than passing it around
to others) is to access fields or methods of the object to which the reference refers.
Much has been made of the security aspects of Java references. By having references rather
than pointers and not allowing arithmetic on references, the Java environment avoids a lot of
the bugs and security vulnerabilities that are caused by allowing such manipulation in C or
C++. But this is a bonus outcome, a happy byproduct of Java having references. The real reas-
on references are part of Java is because of garbage collection.
Garbage collection requires that the system know the difference between references to objects
and other forms of data. This allows the system to keep track of what objects are referenced,
and remove objects when there are no longer any references to them. Pointers look just like
integers, and so it is difficult for the system to tell the difference between a real pointer and
something that might be a pointer but is, in fact, simply a value.
Search WWH ::

Custom Search