Static vs Instance Variables: Difference?

Say there is a test class:

class Test{
public static int a = 5;
public int b = 10;
}
// here t1 and t2 will have a separate copy of b
// while they will have same copy of a.
Test t1 = new test(); 
Test t2 = new test();

You can access a static variable with it's class Name like this

Test.a = 1//some value But you can not access instance variable like this
System.out.println(t1.a);
System.out.println(t2.a);

In both cases output will be 1 as a is share by all instances of the test class. while the instance variable will each have separate copy of b (instance variable) So

 t1.b = 15 // will not be reflected in t2.
 System.out.println(t1.b); // this will print 15
 System.out.println(t2.b); / this will still print 10; 

Hope that explains your query.


Suppose we create a static variable K and in the main function we create three objects: ob1 ob2 ob3; All these objects can have the same value for variable K. In contrast if the variable K was an instance variable then it could have different values as: ob1.k ob2.k ob3.k


In the context of class attributes, static has a different meaning. If you have a field like:

private static int sharedAttribute;

then, each and every instance of the class will share the same variable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.

Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a also affects b and you might end up wondering why b changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:

  1. class constants: since they are const, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lot of instances of that class. Not sure about concurrent access, though.
  2. variables that are intended to be shared, such as reference counters &co.

static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.

A static method can only access static attributes, but think twice before trying this.

Rule of thumb: don't use static, unless it is necessary and you know what you are doing or you are declaring a class constant.