Pointers And Memory - Contents
A D V E R T I S E M E N T
Java has pointers, but they are not manipulated with explicit operators such as * and &. In
Java, simple data types such as int and char operate just as in C. More complex types
such as arrays and objects are automatically implemented using pointers. The language
automatically uses pointers behind the scenes for such complex types, and no pointer
specific syntax is required. The programmer just needs to realize that operations like
a=b; will automatically be implemented with pointers if a and b are arrays or objects. Or
put another way, the programmer needs to remember that assignments and parameters
with arrays and objects are intrinsically shallow or shared— see the Deep vs. Shallow
material above. The following code shows some Java object references. Notice that there
are no *'s or &'s in the code to create pointers. The code intrinsically uses pointers. Also,
the garbage collector (Section 4), takes care of the deallocation automatically at the end
of the function.
public void JavaShallow() {
Foo a = new Foo(); // Create a Foo object (no * in the declaration)
Foo b = new Foo(); // Create another Foo object
b=a; // This is automatically a shallow assignment --
// a and b now refer to the same object.
a.Bar(); // This could just as well be written b.Bar();
// There is no memory leak here -- the garbage collector
// will automatically recycle the memory for the two objects.
}
The Java approach has two main features...
- Fewer bugs: Because the language implements the pointer manipulation
accurately and automatically, the most common pointer bug are no longer
possible, Yay! Also, the Java runtime system checks each pointer value
every time it is used, so NULL pointer dereferences are caught
immediately on the line where they occur. This can make a programmer
much more productive.
- Slower:
Because the language takes responsibility for implementing so
much pointer machinery at runtime, Java code runs slower than the
equivalent C code. (There are other reasons for Java to run slowly as well.
There is active research in making Java faser in interesting ways — the
Sun "Hot Spot" project.) In any case, the appeal of increased programmer
efficiency and fewer bugs makes the slowness worthwhile for some
applications.
Back to Table of Contents
A D V E R T I S E M E N T
|
Subscribe to SourceCodesWorld - Techies Talk |
|