Using Static Variables in Java
Last Updated :
22 Sep, 2021
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).
Example
Java
class emp {
int id;
String name;
int salary;
static String ceo;
emp( int id, String name, int salary, String ceo)
{
this .id = id;
this .name = name;
this .salary = salary;
this .ceo = ceo;
}
void display()
{
System.out.println( "ID: " + id + ", "
+ "Name:: " + name + ", "
+ "Salary: $" + salary + " & "
+ "CEO:: " + ceo);
}
}
class GFG {
public static void main(String[] args)
{
emp Monodwip
= new emp( 1 , "Monodwip" , 30000 , "Rinkel" );
emp Mukta = new emp( 2 , "Mukta" , 50000 , "Rinkel" );
emp Subham = new emp( 3 , "Subham" , 40000 , "Arnab" );
Monodwip.display();
Mukta.display();
Subham.display();
}
}
|
Output
ID: 1, Name:: Monodwip, Salary: $30000 & CEO:: Arnab
ID: 2, Name:: Mukta, Salary: $50000 & CEO:: Arnab
ID: 3, Name:: Subham, Salary: $40000 & CEO:: Arnab
Output explanation:
From the above output, we can perceive that Rinkel got replaced by Arnab for all the objects, hence justifying the usage of static variable.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...