Using Static Variables in Java
Here we will discuss the static variables in java. Java actually doesn’t have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of static variable, why to incorporate in our program. Now we are taking a real-time example as an illustration here in order to perceive why we are using it.
Illustration: Employee directory
Suppose there are 25 students in the Production Engineering department of NIT Agartala. All students have its unique enrollment number, registration number, and name. So instance data member is good in such a case. Now all instance data members will get memory each time when the object is created. Here, “department” refers to the common property of all the objects. If we make it static, this field will get the memory only once.
Thus static variables can be used to refer to the common property of all objects (which is not unique for each object), for example, college name of students, company name of employees, CEO of a company, etc. It makes the program memory efficient (i.e., it saves memory).
ID: 1, Name:: Monodwip, Salary: $30000 & CEO:: Arnab ID: 2, Name:: Mukta, Salary: $50000 & CEO:: Arnab ID: 3, Name:: Subham, Salary: $40000 & CEO:: Arnab
From the above output, we can perceive that Rinkel got replaced by Arnab for all the objects, hence justifying the usage of static variable.