I thought I understood the difference between local and global variables in java until I saw an example today. In this code one tries to add elements to a link list in a met
This is mixing up variables and objects, newElement
is indeed a local variable and it is lost after the method ends, but the reference points to an object. An object is eligable for garbage collection if no references (variables) point to it. In this case temporarily newElement
and firstElement
both pointed to it. It lost newElement
when the method exited but firstElement
still points to it, as does lastElement
so it isn't eligable for garbage collection.
Or in other words: A variable refers to an object, it is not the object itself.
I build a house and write it's address on a scrap of paper so you can get there, I pass that scrap of paper to you, you write the address from the scrap of paper into your address book, you throw away the scrap of paper.
The demolitions crew checks whether anyone is still using a house by seeing if anyone still holds its address. Even though you threw away the scrap of paper you still have the address in your address book so the house is still being used and is not demolished
newElement
is just a reference to an object created in memory.
firstElement
then holds a reference to the same object.
The reference newElement
is indeed a local variable, but the object referred to by the reference is then also referred to by another reference, i.e. firstElement
. So after the addDataPacket()
method completes, the newElement
reference no longer exists, but the object that it referred to still exists in memory and that object is referred to by firstElement
.