• Post Reply Bookmark Topic Watch Topic
  • New Topic

How Are References Represented in Memory?  RSS feed

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. Yesterday there was a discussion of the following code:

Object o = "test";
String s = (String) o;

My understanding is that o and s reference the "same" object (i.e., "o == s" is true), but s (and not o) can access additional methods of the String class.

Also, I believe that the references are stored on the stack, and the actual objects referenced are stored on the heap.

So evidently, even though o and s point to the same place on the heap, o only "sees" a subset of the object while s "sees" the entire object (e.g., the additional methods).

Somehow the compiler knows this. Can anyone explain how this is done? In other words, how are the differences between o and s represented in RAM?

If there is a good source for this, that would be helpful as well.

Thanks. Mark Dexter
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mark,

The reference to o and s will be the same in RAM. The value in RAM would just be an address representing the location of the Object and String.
The compiler is where the difference is taken into account. You told the compiler that reference "o" is an object of type "Object", and the reference "s" is an object of type "String". So the compiler will only let you perform "Object" methods on "o", and "String" methods on "s".

Clear as mud?

Darrin
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Darrin Cartwright:
Hi Mark,

The reference to o and s will be the same in RAM. The value in RAM would just be an address representing the location of the Object and String.


I don't think Java guarantees anything about how references, or anything, is really stored in RAM. Java is all about specifying the behaviour and not specifying the implementation any more than necessary.

For instance, it says an int must behave as a signed 32-bit integer, but doesn't say it has to take up 32 bits of RAM. It could take more (e.g. 64). It probably won't take less!

That said, I think your explanation does say how it is likely that most real JVMs would work.
 
Mark Dexter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That helps. Mark
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!