It is used for memory management in Java. the following are the Java static keywords which are used i.e.,
>variable(class variable)
>method(class method)
>block
>nested class
JAVA STATIC VARIABLE:
If you declare any variable as static, it is known as a static variable. Let's understand more elaborately about static variables,
The static variable can be used to refer the common property of all objects (that is not unique for each object).
e.g. 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.
ADVANTAGE OF STATIC VARIABLE:
It makes your program memory efficient, i.e. it saves memory.
EXAMPLE OF STATIC VARIABLE
class Student8 {
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
PROGRAM OF COUNTER WITH STATIC VARIABLE
Static variable will get memory only once,if any object changes the value of static variable it will retain its value.
class Counter2 {
static int count=0; //will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
public static void main(String args[]) {
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
JAVA STATIC METHOD
If you apply static keyword with any method, it is known as static method.
>A static method belongs to the class rather than object of a class.
>A static method can be invoked without the need for creating an instance of a class.
>static method can access static data member and can change the value of it.
Example of static method
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
JAVA STATIC BLOCK
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block:
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main
Now, question arise why java main method is static?
It is because the object is not required to call static method if it were non-static method, JVM create object first then call main() method that will lead the problem of extra memory allocation.
Leave Comment