In case of the Instance Variable new operator creates separate memory for each and every Object.
In case of the Static Variables new operator shares the same memory for any number of objects.
The following example shows difference between Instance and Static variable.
class StaticEx
{
StaticEx()
{
static_var++;
instant_var++;
}
public static int static_var=10;
public int instant_var=20;
public void display()
{
System.out.println("static_var value = "+static_var);
System.out.println("instant_var value = "+instant_var);
}
}
class StaticExMain
{
public static void main(String args[])
{
StaticEx staticExObj1 = new StaticEx();
staticExObj1.display();
StaticEx staticExObj2 = new StaticEx();
staticExObj2.display();
StaticEx staticExObj3 = new StaticEx();
staticExObj3.display();
}
}
OUTPUT:
static_var value = 11
instant_var value = 21
static_var value = 12
instant_var value = 21
static_var value = 13
instant_var value = 21
In case of the Static Variables new operator shares the same memory for any number of objects.
The following example shows difference between Instance and Static variable.
class StaticEx
{
StaticEx()
{
static_var++;
instant_var++;
}
public static int static_var=10;
public int instant_var=20;
public void display()
{
System.out.println("static_var value = "+static_var);
System.out.println("instant_var value = "+instant_var);
}
}
class StaticExMain
{
public static void main(String args[])
{
StaticEx staticExObj1 = new StaticEx();
staticExObj1.display();
StaticEx staticExObj2 = new StaticEx();
staticExObj2.display();
StaticEx staticExObj3 = new StaticEx();
staticExObj3.display();
}
}
OUTPUT:
static_var value = 11
instant_var value = 21
static_var value = 12
instant_var value = 21
static_var value = 13
instant_var value = 21