Java_static_keyword
Java_static_keyword
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.
o 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.
o The static variable gets memory only once in the class area at the time of class loading.
Output:
Counter(){
count++;//incrementing value
System.out.println(count);
}
Output:
1
1
1
Program of counter by static 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.
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.
Example of static method
//Java Program to demonstrate the use of a static method.
class Student
int rollno;
String name;
college = "BBDIT";
rollno = r;
name = n;
//creating objects
s1.display();
s2.display();
s3.display();
There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
class A{
int a=40;//non static
package OOPS;
2. Whenever the name of instance and local variable both are same then our
runtime environment (JVM) gets confused that which one is local variable
and which one is instance variable to avoid this problem we will use this
keyword.
package OOPS;
int a;
this1(int a)
{
this.a=a;
}
3. It is used when we want to call the default constructor of its own class.
package OOPS;
public class ThisDefaultConst {
ThisDefaultConst()
{
System.out.println("this is default const");
}
ThisDefaultConst(int a)
{
this();
System.out.println(a);
}
public static void main(String[] args) {
package OOPS;
thisParaConst()
{
this(10);
}
thisParaConst(int x)
{
System.out.println(x);
}
public static void main(String[] args) {