If you declare any variable as static, it is known as a static variable. The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading. It makes your program memory efficient (i.e., it saves memory). Let us understanding the problem without static variable.
Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once. The following is the example of static variable.
Output:
Let us understand as how the keyword static is useful while handing logic in Java programs. The following example deals with a variable counter in a class which is not static.
Output:
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the count variable.
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
Output: