What is the difference between an instance and a class (static) variable in Java

PrimalScientist picture PrimalScientist · Mar 18, 2013 · Viewed 31.4k times · Source

The title of this question is actually a previous examination question and I am looking for clarification / an answer to it.

Please note that I am learning Java and am becoming familiar with its syntax.

I understand that this question may have been asked before and if so can someone please show me where I may access the question if possible? Also please accept my apologies if this is the case. To show that I have been researching this area, my own understanding is that instance variables belong to the objects / instances of a certain class (template) and can be changed (mutated) within that instance / object as and when required.

A class variable is a variable that has only one copy and can be accessed but not be modified (mutated?), but is available to all classes as required?

Am I on the right track here?

Also, what exactly does the 'static' do? Is an instance of a class only static if it resides within the main instance of a class?

Many thanks.

Answer

Ajay S picture Ajay S · Mar 18, 2013

A static variable is shared by all instances of the class, while an instance variable is unique to each instance of the class.

A static variable's memory is allocated at compile time, they are loaded at load time and initialized at class initialization time. In the case of an instance variable all of the above is done at run time.

Here's a helpful example:

An instance variable is one per object: every object has its own copy of its instance variable.

public class Test{

   int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

Both t1 and t2 will have their own copy of x.

A static variable is one per class: every object of that class shares the same static variable.

public class Test{

   public static int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

Both t1 and t2 will share the same x.