1.static keyword is an important element in java which is mainly used for memory management.
2.static keyword can be used with variable,function and block.
3.static members belong to class rather than object of class so they can be called by class name directly
1. static variable
1.The variable which is declared with static keyword is called static variable.
2.It is also called class level variable because it is common to all instances(object).
3.A static variable can be accessed anywhere in the program using class name.
For better understanding see the example below.
class Rectangle
{
//declaring static varibale
static int height,width,ar;
void area()
{
ar=height*width;
System.out.println("Area of Rectangle="+ar);
}
}
class Easy
{
public static void main(String[] args)
{
//accessing static varible and assigning value to it
//note that we are accessing using class name not using object
Rectangle.height=20;
Rectangle.width=30;
//Creating instance(object) of class
Rectangle obj=new Rectangle();
obj.area();//calling function
}
}
/*
### Output ###
Area of Rectangle=600
*/
2. static function
1.The function which is declared with static keyword is called static function or method.
2.A static function is also called by class name directly because it belongs to class rather than object.
class Rectangle
{
//declaring static varibale
static int height,width,ar;
//declaring static function
static void area()
{
ar=height*width;
System.out.println("Area of Rectangle="+ar);
}
}
class Easy
{
public static void main(String[] args)
{
//accessing static varible and assigning value to it
//note that we are accessing using class name not using object
Rectangle.height=20;
Rectangle.width=30;
//Calling static function using class name
Rectangle.area();
}
}
/*
### Output ###
Area of Rectangle=600
*/
3. static block
It is such type of block that executes before the main function.For better understanding see the below example.
class Easy
{
//declaring static block
static
{
System.out.println("I am inside static block");
}
public static void main(String[] args)
{
System.out.println("I am inside main function");
}
}
/*
### Output ###
I am inside static block
I am inside main function
*/
0 Comments