14

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++?

thisisashwani
  • 1,748
  • 2
  • 18
  • 25
auser
  • 6,307
  • 13
  • 41
  • 63

4 Answers4

18

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.

Community
  • 1
  • 1
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
5

What exactly is a reference in Java?

It is an index of an object. It can be thought of as like a pointer but it differs in the fact that it

  • can change at any time.
  • does not always have a direct relationship with memory addresses.
  • is usually 32-bit in a 64-bit JVM.
  • you can't re-interprete what the reference refers to. You can only change the type of the reference itself.

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

Yes.


On Compresses Oops which allows a 64-bit JVM to sue 32-bit references.

Java HotSpotâ„¢ Virtual Machine Performance Enhancements - Compressed Oops

Compressed oops in the Hotspot JVM

IBM V6 - More effective heap usage using compressed references

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
4

Yes, a reference is basically the same thing as a pointer. By the way, if you call a method on a null reference, you get... a NullPointerException.

Note that it doesn't have to be a memory address, though. A given object can be stored elsewhere during a program execution, and still keep the same reference. But you don't need to care, as pointer arithmetic doesn't exist in Java.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

A reference is a "pointer" to a memory address in Java, even though Java eleminates direct manipulation of pointers, unlike C++. Objects in Java are never passed to methods or returned by methods, it is always a reference that is being passed.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Clyde
  • 83
  • 9