File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes instance and static variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "instance and static variables" Watch "instance and static variables" New topic

instance and static variables

vara prasad
Ranch Hand

Joined: Dec 21, 2004
Posts: 47
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

Joined: Jan 29, 2003
Posts: 8791
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.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
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

Joined: Jan 29, 2003
Posts: 8791
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

Joined: Oct 12, 2000
Posts: 5093
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?

I agree. Here's the link:
subject: instance and static variables
It's not a secret anymore!