Question

Can you tell me how long a variable lives in a program (in Java). i.e. variables declared inside methods, variables used in parameters, STATIC variables, variables used to return from a method, etc.

Thanks.

Was it helpful?

Solution

  1. References declared inside methods go out of scope when the method exits.
  2. Parameters passed to methods won't be eligible for GC until there are no more references to them or they go out of scope.
  3. Static references are associated with a class and live as long as the class is loaded.
  4. Returned references won't be eligible for GC until there are no more references to them or they go out of scope.

OTHER TIPS

Objects in Java are guaranteed to live as long as they are referenceable through a transitive closure of the root set. This is a conservative approximation of the application's live objects¹.

Edit: Is this question concerning object lifetime, or variable scope? We have some mixed terminology going on.

¹ A live object is an object that will be referenced again before the application terminates.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top