Instance variables and Class variables (static variables) in Java

Posted on Updated on

Java variables as Instance Variables and Class Variables are widely used in programs. We all know that variables has its own importance in java. In fact any programming language, a very important idea to understand right from the are variables. A variable is essentially a value that has a name attached to it. The value of a variable can generally be changed during the program, and the current value of the variable at any point is referred to via the variable’s name.

Instance Variable –

An instance variable is a variable whose separate copy is available to each object. Instance variable are created in the object on heap memory.

Class variables –

A class variable is a variable whose single copy in memory is shared by all objects. Class variable are stored on  method area.

Since, instance variable will have a separate copy in each object, when the value of an instance variable is modified in an object, it does not affect the instance variable in other objects. This is proved in next program –

Output:

Now, since a class variable or static variable will have only one copy in memory and that is shared by all the object, hence any modification happened in an object will also affect others objects. This is proved in next program –

Output

Stay tuned for more updates!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.