Lab 07 - Java Static Keyword: Objective
Lab 07 - Java Static Keyword: Objective
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
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.
class Student{
int rollno;
String name;
String college="ITS";
}
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.
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.
Counter(){
count++;//incrementing value
System.out.println(count);
}
Output:
1
1
1
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.
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
Output:
1
2
3
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
There are three main restrictions for the static method. They are:
class A{
int a=40;//non static
POST LAB
Question 1:
Question 2:
Question 3:
Question 4: