Memory management of objects in java

java, memory, memory-management, object, reference

Solution

In java you always assign something on the right to a reference to the left.

So you statements say something like this:

- Assign the new `Date` object `Date(12, 31, 1999)` to the variable `a`

- Assign the new `Date` object `Date(91, 1, 2011)` to the variable `b`

- Assign the reference of variable `a` to variable `b`.

So it looks like this if I follow those steps:

`a` -> `Date(12, 31, 1999)`

`a` -> `Date(12, 31, 1999)` `b` -> `Date(1, 1, 2011)`

`a` -> `Date(12, 31, 1999)` `b` -> `Date(12, 31, 1999)`

Please note that after this assignment the original object of `Date(1, 1, 2011)` is no longer referenced since you cannot reach it from your application. Its original referencing variable `b` is overwritten and now the object `Date(12, 31, 1999)` is referenced from both `a` and `b`. `Date(91, 1, 2011)` is orphaned and ready to be garbage collected.

Imagine this as if you were holding a sword and an axe. First you pick up a sword. Then you pick up the axe. After that you drop the sword and drag the axe you still have in your hand with both hands. After that you do not hold the sword you dropped (it is lost).

Edit: This is an error if you tell the author of the book he will be grateful.

Problem

I'm reading this book on data structures and it covers memory management and orphaned objects in Java.The textbook says the following: For example, consider the three assignment statements in the figure at left. After the third assignment statement, not only do a and b refer to the same Date object (1/1/2011), but also there is no longer a reference to the Date object that was created and used to initialize b. The only reference to that object was in the variable b, and this reference was overwritten by the assignment, so there is no way to refer to the object again. Such an object is said to be orphaned. Code: ``` Date a=new Date(12, 31, 1999); Date b=new Date(1, 1, 2011); b=a; ``` Is that statement true? Shouldn't the reference of a (the memory location of object `Date(12, 31, 1999)` be what the reference of b be? This seems like one huge error but there is even a picture showing memory block for 12, 31, 1999 being the orphaned object. Picture: http://imageshack.us/f/818/3tkx.jpg/

Original source