• Post Reply Bookmark Topic Watch Topic
  • New Topic

question about static variable's residence  RSS feed

 
Javed Mohammed
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I understand that an object and its instance variables reside on heap, when the object is created.
Each object will have its own copy of instance variables.

Where and when does a static variable reside. If I am right, it does need an object to be created. Also, when two objects of the class are created, boh objects share the same copy of the static variable. Hence, the static variable is not living inside the object, then where is it?

Thanks and Regards,

Javed.
 
Eric McIntyre
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Javed Mohammed:
Where and when does a static variable reside.
A static variable comes into existence when the class is loaded.

If I am right, it does need an object to be created.
No, a static variable does not need to have any objects created. Any statement that references a class will cause it to be loaded (and therefore init its static members) if it is not already.
or even just
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eric is correct, if he means that the static variables don't need an object of the class that contains them. However, there IS an object created when a class is loaded. The object is of type Class and represents the class. I don't know if static variables are associated with this object or not. This is one nice thing about Java: general you don't have to worry about these details. Of course, it is sometimes interesting to learn about just as an academic pursuit.

Layne
 
Javed Mohammed
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OOPS.......I did mean to say that static varibales does not need an object, that was a typing mistake.

"An object is created when class is loaded", this answers my queston.

Thanks everybody.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to clarify, let's say you have a class named MyClass. The object created that I mentioned is NOT an object of type MyClass. It is an object created from java.lang.Class. This object represents the MyClass type.

Like I said, I am not sure if the static variables are associated with this class or not. You may want to check out the Java Language Specification (JLS) to see what it says.

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!