Intro of JAVA
Learn Java
Static keyword is used for memory management purpose.Static keyword belongs to class rather than instance of class(i.e object).By applying Static keyword with variables,method,block,nested class we can make available them for entire class rather than instance of class.So,Static can be:-
If you declare variable as static,its known as static variable and static variable value remain constant throughout class ,it will not vary for class and instance of class.
Count program without static variable in which counts get incremented every time separately when we invoke object.
class College{
int count=0;
College(){
count++;
//incrementing value
System.out.println(count);
}
public static void main(String args[]){
//Creating objects
College c1=new College();
College c2=new College();
College c3=new College();
}
};
Output
Count program with static variable which makes variable available for entire class.
class College{
Static int count=0;
College(){
count++;
//incrementing value
System.out.println(count);
}
public static void main(String args[]){
//Creating objects
College c1=new College();
College c2=new College();
College c3=new College();
}
};
Output
Method with static keyword is known as Static method.
Static method program:
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
};
Output:
Used to initialize static data member. It is executed before main method at time of classloading.
Static block program:
class A2{
static{System.out.println("static block");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output: