the static keyword
The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods and blocks. The static keyword belongs to the class than instance of the class. The static can be:
1) 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.
2) The static variable gets memory only once in class area at the time of class loading.
class Student{
int id;
String address;
static String college ="Rkgit";
Student(int id,String address){
this.id=id;
this.address=address;
}
void displayRecord(){
System.out.println(id+" "+address+" "+college);
}
public static void main(String args[]){
Student s1=new Student(112,"new delhi");
Student s2=new Student(119,"ghaziabad");
s1.displayRecord();
s2.displayRecord();
}
}
Static method :
class A{
static int cube(int n){
return (n*n*n);
}
public static void main(String args[]){
System.out.println(cube(3));
}
}
1) It is used to initialize the static data member.
2) It is excuted before main method at the time of classloading.
class A{
static {
System.out.println("static block is executed");}
public static void main(String args[]){
System.out.println("main method executed");
}
}
JAVA TUTORIALS HOMEPAGE
- variable
- method
- block
Static variable :
If you declare any variable as static, it is known static variable.
2) The static variable gets memory only once in class area at the time of class loading.
class Student{
int id;
String address;
static String college ="Rkgit";
Student(int id,String address){
this.id=id;
this.address=address;
}
void displayRecord(){
System.out.println(id+" "+address+" "+college);
}
public static void main(String args[]){
Student s1=new Student(112,"new delhi");
Student s2=new Student(119,"ghaziabad");
s1.displayRecord();
s2.displayRecord();
}
}
Static method :
If you apply static keyword with any method, it is known as static method.
1) A static method belongs to the class rather than object of a class.
2) A static method can be invoked without the need for creating an instance of a class.
3) Static method can access static data member and can change the value of it.
class A{
static int cube(int n){
return (n*n*n);
}
public static void main(String args[]){
System.out.println(cube(3));
}
}
Static block :
1) It is used to initialize the static data member.
2) It is excuted before main method at the time of classloading.
class A{
static {
System.out.println("static block is executed");}
public static void main(String args[]){
System.out.println("main method executed");
}
}
JAVA TUTORIALS HOMEPAGE
0 comments: