What's the lifetime of variables?

During the execution of a Java program, each variable has its own time within which it can be accessed. This is called the lifetime of the variable. We can determine the lifetime of variables by looking at the context in which they're defined. Anyway, we can distinguish between three contexts:

Instance variables:
Instance variables are class members. Every time you create an object from a class, a brand new copy of these instance variables is created for this object. Actually, creating an object from a class means, partially, creating copies of instance variables for that object. So each object has its own copy of instance variables which exist as long as the object they belong to exists. The values of these variables constitute what we call: the state of the object.

Static variables:
Static variables are also members of a class but can't belong to any object created from that class. So created objects from the class don't get their own copies of static variables. Therefore static variables are created only when the class is loaded at runtime. The existence of static variables is dependent only on the class itself. As a result, a static variable exists as long as its class exists.

Please note that an object of a class may still manipulate a static variable even though this object can't have its own copy of this static variable.

Local variables:
Also called automatic variables, are called local because their scope is the method or block within which they are declared. After the execution of the method or block completes, these local (non-final) variables are no longer accessible.

1 comment:

Lakindu said...

thanks a lot! please can you explain Static variables little bit more with a example?