Example of a class variable (static variable)

This Java programming example will teach you how you can define the static class variable in a class. When a number of objects are created from the same class, each instance has its own copy of class variables. But this is not the case when it is declared

Example of a class variable (static variable)

This Java programming example will teach you how you can define the static class variable in a class. When a number of objects are created from the same class, each instance has its own copy of class variables. But this is not the case when it is declared

Example of a class variable (static variable)

Example of a class variable (static variable)

     

This Java programming example will teach you how you can define the static class variable in a class. When a number of objects are created from the same class, each instance has its own copy of class variables. But this is not the case when it is declared as static static.

static  method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded. Remember, each time you call the instance the new value of the variable is provided to you. For example in the class StaticVariable each instance has different copy of a class variable. It will be updated each time the instance has been called. We can call class variable directly inside the main method.

To see the use of a static variable first of all create a class StaticVariable. Define one static variable in the class. Now make a  constructor  in which you will increment the value of the static variable. Now make a object of StaticVariable class and call the static variable of the class. In the same way now make a second object of the class and again repeats the process. Each time you call the static variable you will get a new value.

Code of this example is given below:

public class StaticVariable{
  static int noOfInstances;
  StaticVariable(){
  noOfInstances++;
  }
public static void main(String[] args){
 StaticVariable sv1 = new StaticVariable();
 System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

 StaticVariable sv2 = new StaticVariable();
 System.out.println("No. of instances for sv1 : "  + sv1.noOfInstances);
 System.out.println("No. of instances for st2 : "  + sv2.noOfInstances);

 StaticVariable sv3 = new StaticVariable();
 System.out.println("No. of instances for sv1 : "  + sv1.noOfInstances);
 System.out.println("No. of instances for sv2 : "  + sv2.noOfInstances);
 System.out.println("No. of instances for sv3 : "  + sv3.noOfInstances);
 }
}

Output of the program is given below:

As we can see in this example each object has its own copy of class variable.

C:\java>java StaticVariable
No. of instances for sv1 : 1
No. of instances for sv1 : 2
No. of instances for st2 :  2
No. of instances for sv1 : 3
No. of instances for sv2 : 3
No. of instances for sv3 : 3

Download this example: