This question already has an answer here:
-
How does the static keyword work in Java?
4 answers
class A{
static int a=5;
int b=6;
void method(){
//method body
a++;
}
}
How JVM handles static variable handles static variable. for example...
A object1=new A();
A object2=new A();
Above code will create two objects of class A in two different memory location. Also two instance of variable b
will be created. What will happen for variable a
. which object will hold the reference for the static variable? and what happen when we update static variable?
"which object will hold the reference for the static variable"
Objects don't hold static variables as they are not bound to any object, they are bound to class.
Classes and all of the data applying to classes (not instance data) is stored in the Permanent Generation section of the heap.
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
There will only be one copy of the variable a
, which is shared between all instances of class A
.
Static member variables are class variables. They don't exist in any of the instances (objects) of the class - so there is not an A
object which holds the variable.
See Oracle's Java Tutorials: Understanding Class Members
A static variable is related to a class not in the instance, so both instances of A will share the static variable.
Another example, if you need to syncronize (using synchronized) to access a static variable, you have to keep in mind that the lock is static, so the lock is shared with all the instances.
Straight forward answer
"All static data stored in context of a class(which is global memory) and All object data like instance variables(which is specific to each object--own copy) stored in Object scoped memory"
changes to static variables will reflect to all objects bcz it's a global memory and changes to instance variable is specific to object level
A object1=new A(); a=5 b=6
A object2=new A(); a=5 b=6
object1.method(); a=6 b=6
object2.method(); a=7 b=6