• Post Reply Bookmark Topic Watch Topic
  • New Topic

java lifetime of objects  RSS feed

 
Derryl Larson
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,
I was wondering about how the Java-compiler manages the lifetime of objects.
Aren't the variables a, b and, therefore, the objects A(i),B(i) destroyed after each iteration of the loop?
Why then does the toString-method print out A(4), B(4) after finishing the for-loop?
Code:

 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please copy the output and paste it here showing what you are talking about.
The variables a and b are defined outside of the loop. Any values they are assigned inside of the loop will remain after the loop.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Norm's right. The variables don't go out of scope until the end of the method.

However, every A and B object except the last pair have no remaining references to them once a and b have been reassigned. That means that they are eligible for garbage collection once that's happened. They might not be - garbage collection is only done when necessary - but they are eligible.
 
Paul Clapham
Sheriff
Posts: 22823
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also when you're thinking about that sort of questions, don't get variables and objects mixed up in your mind. The variables aren't the objects, they only contain references to the objects. So in your example several A and B objects are created, but there are only two variables which each hold references to only one of those objects at any particular time.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler does nothing with the lifetime of objects. That is the JVM, with automatic garbage collection, but it usually only happens when you start to run short of memory.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!