static variables are attached 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 Static Variable 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.(If your not familiar with the words constructor and object, please don't worry I'll explain you these things in next lessons. In here i'm only giving you a brief introduction about variables. )
static variable has default value. It is 0. Try this simple program. Then you can see it.
class Static{
static int x;
public static void main(String args[]){
System.out.println(x);
}
}
Thank you



ela machan, really useful :)
ReplyDelete