Thursday, November 1, 2012

Java variables

Cup Size -- a story about variables

1.In Java, objects are created on the heap 
 In Java, if you want to stick an object in a variable, remember that the object is created out on the garbage-collectible heap. Always. 

2. References
References store a value which the Java Virtual Machine (JVM) uses to get to your object. It sure looks and feels a lot like a pointer, and it might very well be a pointer to a pointer, or...
You Can't Know. It's an implementation detail that you, as a programmer, can't access. Don't even think about it. There's no way to use that value other than to access the methods and variables of the actual object the reference refers to. That's part of what makes Java safer than C/C++. You can not go directly to any arbitrary memory location. The JVM allocates memory on your behalf, for your object, and stores an address-like thing in the reference cup (which is most likely a 32-bit cup, but not guaranteed to be).


Pass-by-Value Please (Cup Size continued)

How does pass-by-value work with references?
Java passes everything by value.
With primitives, you get a copy of the contents. 
With references you get a copy of the contents.
When you pass an object reference into a method, you are passing a COPY of the REFERENCE.  A clone of the remote control. 
The object is still sitting out there, waiting for someone to use a remote.The object doesn't care how many remotes are "programmed" to control it. Only the garbage collector cares (and you, the programmer).

No comments:

Post a Comment