Static keyword concept in Java |

Static keyword concept in Java
concept 1 : When we use Static keyword in class definition then JVM will allocate only one memory location for that and all object will take copy of that  i.e. for each object there is no own property of that define static in class definition.
Code :
 package com.stat;
public class staticTest {
public  int k=9;
public int getNum()
{
 return this.k;

}
public void setNum(int a)
{
 this.k=a;
}
public static void main(String [] args)
{

 staticTest st1= new staticTest();
 staticTest st2= new staticTest();
 System.out.println("the value of k ="+st1.k);
 st2.setNum(27);
 System.out.println("the value of k ="+st2.k);
 System.out.println("the value of k ="+st1.k);

}
}
Output :
    
      the value of k =9
      the value of k =27
      the value of k =9
Exp:  here from object st1 coming value 9 , after modify value to 27 . again it value comes 9 i.e. for each object there is own copy of int k.
Code :
    package com.stat;
public class staticTest {
public static int k=9;
public int getNum()
{
 return this.k;

}
public void setNum(int a)
{
 this.k=a;
}
public static void main(String [] args)
{

 staticTest st1= new staticTest();
 staticTest st2= new staticTest();
 System.out.println("the value of k ="+st1.k);
 st2.setNum(27);
 System.out.println("the value of k ="+st2.k);
 System.out.println("the value of k ="+st1.k);

}
}
output:

the value of k =9
the value of k =27
the value of k =27
Exp : when we declare int k to staic the JVM will allocate memory once for K and all object created of class will copy of that k , so when we modify the value
        will effect for every object.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.