If you are an experienced C/C++ programmer, then you know that these languages
provide support for pointers. The reason for this is simple: Java does not support or allow pointers. (Or
more properly, Java does not support pointers that can be accessed and/or modified
by the programmer.) Java cannot allow pointers, because doing so would allow Java
applets to breach the firewall between the Java execution environment and the host
computer. (Remember, a pointer can be given any address in memory—even addresses
that might be outside the Java run-time system.) Since C/C++ make extensive use of
pointers, you might be thinking that their loss is a significant disadvantage to Java.
However, this is not true. Java is designed in such a way that as long as you stay within
the confines of the execution environment, you will never need to use a pointer, nor would
there be any benefit in using one. For tips on converting C/C++ code to Java
The Java language does _not_ provide pointers. Instead all objects are handled by references not to be confused with pointers or C++ references. The difference is that Java references do not refer directly to the memory location but rather contain the pointer to the actual memory location which the programmer cannot get direct access to. This extra level of indirection is required for GC to work. When GC kicks in and frees objects that are no longer in use it then does heap compaction to defragment the heap. To do this some objects must be moved around in memory. This is possible because there is only one place where this pointer is located in the reference and thus the memory can be relocated old location freed and pointer changed. In C++ this is not possible because pointers are copied all over the code.
ReplyDeleteIt is also true that pointers are dangerous and lead to memory leaks memory corruption invalid memory access e.g. from uninitialized and improperly initialized variables indexing out of bounds and many bugs due to pointer arithmetic. References and other features related to these avoid all these problems.