Does Java have pointers?

Most guys would say “No, but C++ has pointers” and they are right, but not in the way they assume it. Java has two sorts of data types: primitive types and reference types.


Primitive types are just values on the stack, e.g. boolean, byte, char and int. They are definitely no pointers. 🙂


Reference types keep just an address to the real data at another location. (Common memory management: address on stack and real data on (managed) heap.) This may sound like a pointer, but the language isn’t providing any semantic to perform pointer artrithmetic and therefore is just a reference.

By the way if you use the assignment operator on another reference type you will reference to its data. The default way to get a copy of another reference type is the usage of the method clone. (The default implementation of clone does a shallow copy. If you want something different you have to implement it by yourself.)


public class Example
{
    public static void main(String[] args)
    {
        int num = 42;
        String str = "Text";
    }
}

Before leaving the main function its stack frame contains as local variables the number 42 and the reference to the string “Text” on the heap. After leaving the main function its stack frame gets cleared which includes the number and the reference, but not the actual string on the heap itself. The afterward unreferenced string on the heap gets cleared as soon as the next tracing garbage collection cycle kicks in.


Summa summarum: Java has just references and no pointers.