Java static variable

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.


\begin{lstlisting}
class Student{
int rollno;
String name;
String college=''ITS'';
}
\end{lstlisting}

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.


\begin{lstlisting}
//Java Program to demonstrate the use of static variable
cla...
...dent.college=''BBDIT'';
s1.display();
s2.display();
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
111 Karan ITS
222 Aryan ITS
\end{lstlisting}

Figure 4.5: Static keyword
Image staticvariable

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.


\begin{lstlisting}
//Java Program to demonstrate the use of an instance variable...
...
Counter c2=new Counter();
Counter c3=new Counter();
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
1
1
1
\end{lstlisting}

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.


\begin{lstlisting}
//Java Program to illustrate the use of static variable which...
...ounter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
1
2
3
\end{lstlisting}