Search code examples
javareference

What exactly is a reference in Java?


What exactly is a reference in Java? Is it a memory address? Is a Java reference the equivalent of a dereferenced C++ pointer?

In other words, given the following:

Object o1 = new Object();
Object o2 = new Object();

o1 == o2

Is the above comparison the equivalent of comparing two pointers in C++?


Solution

  • o1 == o2 is pretty much equivalent to comparing two pointers in C/C++, yes.

    But there are a two main differences between references in Java and pointers in C/C++ that are quite important:

    • Java references can't do pointer arithmetic: you can't "add 3" to a reference, you can only let it point to another (known) object
    • Java references are stongly typed: you can't "reinterpret" what lies on the other end of a reference unless you reinterpret it as a type that that object actually is.

    Also a short note about the word "reference": C++ has references that act quite differently from both pointers in C and references in Java (but I don't know enough about C++ to tell you the specifics).

    For a thorough discussion of this, see this related question on programmers.SE.