Java Reference
In-Depth Information
I need to emphasize the importance of the difference between a variable
that is a reference and a variable that is a primitive data type. (Those of
you that are familiar with C++ should definitely pay attention here
because what I am about to say is not true for C++.) A variable in Java is
either one of the eight primitive data types or it is a reference to an
object. Those are your only two options.
If the variable is a primitive data type, the value of that variable is stored
in the same memory location as the variable.
If the variable is a reference, the value of that variable is a memory
address. This memory address is the location of the object that the
reference refers to. The object contains the actual data.
Classroom Q & A
Q: Wait a minute. Isn't a reference just another name for a pointer?
A: No. Sun has made specific efforts to not use the term pointer in
Java. A pointer is a term used to describe a variable that points to
a certain memory address. A reference is a variable that refers to a
particular object.
Q: That doesn't sound different at all. You just said a reference con-
tains a memory address.
A: You're right. It is a subtle difference, but an important one to
understand when learning Java. Both pointers and references are
32- or 64-bit integer values that contain a memory address. How-
ever, pointers can be treated as integers in other languages, allow-
ing for tasks such as pointer arithmetic. Also, in other languages, a
pointer can point to a primitive data type. In Java, a reference can
either refer to an object or null. Also, there is no such thing as
pointer arithmetic in Java. Unlike pointers, you cannot see the
actual value of a reference. So, although a reference is a memory
address, nowhere in your code can you take advantage of that
fact.
Q: Why not just cast the reference to an int and view it that way?
A: Nice try, but the compiler won't let you cast a reference to any
numeric value. Not allowing programmers direct access to mem-
ory is one of the security features of Java, and it also leads to more
stability in your programs. With pointers, it is easy to run off the
end of an array or alter memory that you had no business access-
ing. These are issues that cannot occur in a Java program.
Search WWH ::




Custom Search