Saturday, December 9, 2017

Static Variables in Java with Example

Like an instance variable, static variable (class variable) is declared inside a class but outside any method.keyword static is used while declaring static variable. The generic syntax
of declaring static variable is given below:

       static type variableName;

 where type is one of the types like int,double,float, etc. The difference between instance variable and static variable is as follows:

 1. Every object has its own copy of all instance variables of the class.
 2. All objects of the same class share only one copy of static variable.

 A static variable can be accessed independent of any object. You can access a static variable before any object is created.

 Advantage of static variable to make memory efficient or to save memory.

 Use of static variable to count the Objects:

 class Books{

 static int count=0;

 Books(){

 public static void main(String args[]){

      Books b1 = new Books();
      Books b2 = new Books();
      Books b3 = new Books();
 }

}

 }

 Output:1
             2
            3

No comments:

Post a Comment