Sunday, May 02, 2010

Are Java references "pointers"?

The difference between Java references and C++ pointers is a much-discussed topic on the Internet. Java purists mostly shun the word "pointer" as a historical abomination that made code insecure. They insist on never calling a Java reference a pointer. However, I found it interesting that Java has a NullPointerException class - not a NullReferenceException.

A few days ago, I happened to come across an article titled "Java is Pass-by-Value, Dammit!" that gave me a part of the answer. In it, Scott Stanchfield tries to clear the confusion about Java's parameter passing - pass-by-reference or pass-by-value - and in doing so, shows that Java references act more like C/C++ pointers than C++ references. The article also mentions NullPointerException in passing and provides a quote from the Java Language Specification (JLS) , 3rd Edition as part of the legacy of pointers in Java. The JLS states (at - emphasis not mine):
"The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object."

However, Java does not allow pointer arithmetic as C++ does. Probably to emphasize this and to distance Java from C++, Sun later tried to create a distinction between Java references and pointers. To be fair to Sun, there is a subtle difference between Java references and C++ pointers but it is in the way they are implemented. This is explained in the Best Rated Answer on the page However, the behavior of both is the same, as far as programming with them is concerned (except that many memory-related problems are avoided by eliminating pointer arithmetic).