views:

236

answers:

2

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.

+2  A: 
  1. Variables declared inside methods go out of scope when the method exits.
  2. Parameters won't be eligible for GC until there are no more references to them or they go out of scope.
  3. Static variable are associated with a class and live as long as the class is loaded.
  4. Return values won't be eligible for GC until there are no more references to them or they go out of scope.
duffymo
You are confusing variables (1 and 3) with objects (2 and 4).
starblue
A: 

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.

280Z28
re: mixed terminology. No kidding. I like the way duffymo's answer toggles back and forth between the two. :-)
Laurence Gonsalves