basically the static keyword is used to memory management in java.we can apply static keyword with variables, method, block, nested classes.the static keyword belong to the class that an instance of that class.
the static keyword is also known as class variable.
and also known as class method, block and nested class.
if you declare a variable as static it known as static variable.
that static variable is also used to reference to the common property of all object.which is not same for all object.all object having same static variables.
static variable is so efficient in memory.it gate memory only one time in the class, at the time of class loading.
mane advantage of static variable is it make your program so efficient in memory management.
syntax of static variable:
class student{
int rollno;
string name;
string college="ITS";
}
Code :
class staticdemo
{
static int a=42;
static int b=99;
static void callme()
{
System.out.println("a="+a);
}
}
class staticvariable
{
public static void main(String[] args) {
staticdemo.callme();
System.out.println("b="+staticdemo.b);
}
}
Output :-
//Program to illustrate the use of static data member
class base
{
static int c;
base()
{
c++;
}
static void display()
{
System.out.println("Hi I am in base class"); System.out.println("The value of static data member is
"+c);
}
}
class staticmember
{
public static void main(String[] args)
{
base b1=new base();
b1.display();
base b2=new base();
base b3=new base();
b1.display();
base b4=new base();
base.display();
}
}
Output :-
0 Comments