Java has pointers. People who say that Java does not have pointers are lying. The most confusing point is that, pointers in Java are not called pointers, but called “references” instead. However, a reference is completely different from a pointer.
Although Java does not have a syntax for pointers, it requires that all objects to be accessed through a pointer. For example:
d as a pointer to a
Dog object, which is semantically identical to C++ code
Dog *d; // (1)
There is no way to put a
Dog object into a variable. Instead, ALL objects are allocated in the heap, and accessed by pointers to them.
d = new Dog();
Dog object is created in the heap, and the pointer to that object is returned by the
new operator, which is saved to
d variable, which is equivalent to C++ code
d = new Dog;
If we pass
d into a function, the pointer value is copied into the function (pass-by-value). If the function changes the
Dog object pointed by the parameter, the changes to the
Dog object can be seen outside since only the pointer is copied, but not the object itself. However, if the function assigns something to the parameter, the value of
d will not change, since the value of
d is copied to the parameter.
In Java, ALL variables declared to be an object type are pointers. Although in implementation they may not be direct memory addresses, it is completely transparent to the programmer. You can always think that they are some sort of address, which may be
null (a pointer which does not point to anything). Deferencing a
null pointer will get a
NullPointerException! Although Java does not have pointer arithmetic, the absence of it does not change the fact that object variables are pointers. Also, in Java, unlike in C++, variables are not objects, therefore, we cannot take the address of a variable and store it into a pointer, and we cannot dereference a pointer to store the object pointed in a variable. (Although in C++ we can take addresses of functions and store them into function pointers, functions are not objects and the semantics of function pointers are different from regular object pointers.)
Then, what does the term “reference” mean? In C++, if we declare
int &b = a;
a are identical in ALL aspects. Their addresses are the same because they are the same object. If we pass an object into a reference parameter, the object is not copied and the parameter will BECOME the passed object, which forms the basis of passing by reference and hence the swap function.
- Java is Pass-by-Value, Dammit! (http://javadude.com/articles/passbyvalue.htm)