views:

154

answers:

4

We know that the object reference variable holds bits that represent a way to access an object.

It doesn't hold the object itself, but it holds something like a pointer or an address.

I was going through the Head-First Java (2nd edition) book and in the book it is written that

"In Java we don't really know what is inside a reference variable. We do know that whatever it is, it represents one and only one object. And the JVM knows how to use the reference to get to the object." - Chapter 3 (page 54)

I want to ask:

  • Do an object reference variable holds Pointer, Address or what?
  • How does JVM interpret that?
+2  A: 

That's up to the JVM. A Java reference isn't guaranteed to have any semantics besides that you can access an object through it. Sunacle might do that differently to IBM as well.

In practice it may often be a pointer of some sort, though maybe not directly to the object since that can be moved by the GC.

Joey
A legitimate question would be "how are references implemented in <insert JVM vendor here>'s JVM" though.
Samuel_xL
@Samuel - it depends on how you define "legitimate". Unless you're looking to modify the JVM itself there's no practical use for this information. Curiousity is fine, but these kind of questions always make me think that someone is clinging to a C mindset.
Andrzej Doyle
+2  A: 

It's entirely JVM specific. It may be an address, a pointer, or something more complicated. You don't have, or need, any harder guarantees than the fact that you can get an Object using the reference.

GaryF
+6  A: 

It's entirely up to the JVM to determine what goes inside a reference.

In the simplest case it would just be a pointer (i.e. an address). In more sophisticated cases, the VM may use different representations depending on the situation - for example, you may want to read the paper on "Compressed oops in HotSpot" to see how the HotSpot VM can avoid doubling the size of references in some (but not all) places when running as a 64-bit VM.

The important thing is that you should neither know nor care. As far as you're concerned as a programmer, it's just an opaque set of bits - its only purpose is to let you get to the object in question (or identify a null reference).

Jon Skeet
Okay, Thanks :)
Chankey Pathak
A: 

It's up to the JVM to decide exactly how the reference is implemented.

Having said that, any "sane" implementation would probably use either a direct pointer or some form of compressed pointer for performance reasons. I believe this applies to all current production JVMs.

mikera