Friday, 15 April 2016

Static variable example

Static variable example


  • static variable will get the memory only once in class area at the time of class loading, if any object changes the value of the static variable, it will retain its value.

  • The static variable can be used to refer the common property of all objects (that is not unique for each object)                                                                                       e.g. company name of employees,college name of students etc.


With out static variable

Instance variable count gets the memory at the time of object creation, each object will have the copy of the instance variable(count ). So one object won't reflect to other object.

public class Test{
int count =0;
Test(){
count++;
System.out.println("count: "+count);
}
public static void main(String[] args) {
Test test = new Test();
Test test2 = new Test();

}
}

Output:
count: 1
count: 1
--------------------------------------------------------------------------------------------------------------------------

With static variable


Here when second object is created, because of count is static count is 1(retained) , so in constructor it will increment to 2.

public class Test{
static int count =0;
Test(){
count++;
System.out.println("count: "+count);
}
public static void main(String[] args) {
Test test = new Test();
Test test2 = new Test();

}

}

Output:
count: 1
count: 2


No comments:

Post a Comment