

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Are there pointers in Java? The short answer is “no, there are none” and this seems to be obvious for many developers. That is because the references that Java uses to access objects are very similar to pointers. If you have experience with C programming before you use Java, it may be easier to think about the values that are stored in the variables as pointers that point to some memory locations holding the objects. And it is more or less ok. That is what we will look at now.
There are two major differences.
When you have an array of a struct in C, the memory allocated for the array contains the content of the structures one after the other. If you have something like struct circle { double radius; double x,y; } struct circle circles[ 6 ]; it will occupy 63sizeof(double) bytes in memory (that is usually 144 bytes on 64 bit architecture) in a continuous area. If you have something similar in Java, you need a class (until we get to Java 10 or later): class Circle { double radius; double x,y;
} and the array Circle circles[ 6 ]; will need 6 references (48 bytes or so) and also 6 objects (unless some of them are null) each 24bytes data (or so) and object header (16bytes). That totals to 288bytes on a 64bit architecture and the memory area is not continuous. When you access an element, say circles[n] of the C language array the code uses pointer arithmetic. It uses the address stored in the pointer circles adds n times sizeof(struct circle) (bytes) and that is where the data is. The Java approach is a bit different. It looks at the object circles, which is an array, calculates the n-th element (this is similar to C) and fetches the reference data stored there. After the reference data is at hand it uses that to access the object from some different memory location where the reference data leads. Note that in this case the memory overhead of Java is 100% and also the number of memory reads is 2 instead of 1 to access the actual data.
Java references are not pointer. They contain some kind of pointer data or something because that comes from the nature of today computer architecture but this is totally up to the JVM implementation what it stores in a reference value and how it accesses the object it refers to. It could be absolutely ok though not too effective implementation to have a huge array of pointers each pointing to an object of the JVM and the references be indices to this array. In reality JVM implement the references as a kind of pointer mix, where some of the bits are flags and some of the bits are “pointing” to some memory location relative to some area.