How JVM handles static variable? [duplicate]

2019-05-29 20:05发布

This question already has an answer here:

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?

标签: java static
4条回答
够拽才男人
2楼-- · 2019-05-29 20:58

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.

查看更多
劫难
3楼-- · 2019-05-29 21:02

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

查看更多
祖国的老花朵
4楼-- · 2019-05-29 21:02

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

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-05-29 21:05

"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

查看更多
登录 后发表回答