The static variable in Java is used for memory management mostly. We can use static keywords with variables, methods, and nested classes. This tutorial will discuss Static Variable and Static Methods.
What is a Static Variable?
If any variable is, declared static, then it is called a static variable. The static variable gets memory only once in the class area at the time of class loading.
Static variables belong to the class itself, they can be accessed directly using the class name without creating an object/instance of that class.
Assume in a college, there are 250 students. Each student has a unique name & roll no, so when the objects are created all the instance data members will get the memory. However, the college name is the same for all the students. Then we do not need to allocate memory 250 times for the students. Therefore, it is advisable to make the college static variable, which means the variable is created once and used by all students.
Below is an example of a static variable.
public class Student {
int rollNo;
String name;
static String college = "Trinity"; // Static Variable
Student(int r, String n) // Constructor
{
rollNo = r;
name = n;
}
void displayInformation() {
System.out.println("Roll_No: " + rollNo + ", Name: " + name + ", College: " + college);
}
public static void main(String[] args) {
Student S1 = new Student(111, "Tom");
Student S2 = new Student(222, "Terry");
S1.displayInformation();
S2.displayInformation();
}
}
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-24.png?w=854)
What is the Static Method
If any method is declared static, then it is called a static method. A static method belongs to the class not to the object of the class.
A static method can be accessed without creating the object of the class.
The static method can access data members and can change their value of it.
public class Student {
int rollNo;
String name;
static String college = "Trinity"; // Static Variable
Student(int r, String n) // Constructor
{
rollNo = r;
name = n;
}
static void change() {
college = "CITM";
}
void displayInformation() {
System.out.println("Roll_No: " + rollNo + ", Name: " + name + ", College: " + college);
}
public static void main(String[] args) {
change(); // Calling Static method
Student S1 = new Student(111, "Tom");
Student S2 = new Student(222, "Terry");
S1.displayInformation();
S2.displayInformation();
}
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-25.png?w=747)
In the above example, change() is a static method, and it is accessed without creating the object.