Local VS global variables in Java

后端 未结 2 870
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 15:53

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

相关标签:
2条回答
  • 2020-12-18 16:00

    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.

    An analogy:

    • variable: piece of paper you can write an address on
    • object: house
    • garbage collector: demolitions crew

    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

    0 讨论(0)
  • 2020-12-18 16:16

    enter image description herenewElement 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.

    0 讨论(0)
提交回复
热议问题