Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 828
PrimalScientist Avatar asked Mar 18 '13 20:03

PrimalScientist


2 Answers

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.

like image 120
Ajay S Avatar answered Oct 28 '22 02:10

Ajay S


You can make multiple instances of your class. When you declare an instance variable, each instance gets its own unique copy of that variable. When you declare a static variable, it is the same variable and value for all instances.

public class Foo
{
    public int instanceVariable;
    public static int staticVariable;
}

Foo instance1 = new Foo();
Foo instance2 = new Foo();
instance1.staticVariable = 1;
instance1.instanceVariable = 2;
instance2.instanceVariable = 3;

instance1.staticVariable == 1 // true
instance2.staticVariable == 1 // true

instance1.instanceVariable == 2 //true
instance2.instanceVariable == 3 //true
like image 27
Robert Harvey Avatar answered Oct 28 '22 02:10

Robert Harvey