Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance and static variables

 
vara prasad
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
where the memory for instance and static variables are allocated?
Explain about stack and heap? From which retrieving of variables is faster?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer is instance variables are on the heap and local variables and parameters inside a method are on the stack. The even shorter answer is we don't care.

What's important is the visiblity and scope or life cycle. Instance variables are visible to all methods, maybe to other classes and have the same life span as the object itself. Local variables are visible only inside the current thread inside the method and go out of scope when the method returns.

Let me know if that made sense.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stan, vara said static -- not local.

The space for static variables is allocated when the class is loaded, and it should be in the heap. Instance variables are stored with each instance of a class, also no the heap. The time to retrieve either should be the same.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, David! Sticking with my obsession with visbility and lifespan, statics introduce some rather trickier concepts of storing things on the Class rather than on an instance.

I tend to think of heap and stack as a JVM implementation detail, not one I should have to worry about. Maybe that comes from growing up on mainframe languages that didn't have such things. I'm kinda put off when a language requires me to think about them, and Java is pretty darned good at letting me forget them.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In fact, given that static members do not require lookup of a specific class instance it is quite possible that they're just ever so few nanoseconds faster to call than instance members

I've been told microoptimisation is bad, maybe nanooptimisation is better?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic