How JVM allocates memory to static String variables?

Since JVM allocates memory to static variable type in Method Area . But when it comes to static String type does it refer to heap area from method area or it provides memory in Method Area there itself. If it refer to heap area then String will have the same behaviour(for below example)?

Example:

static String s1 = new String("Aman");
static String s2 = "Aman";

You are conflating the variables s1 and s2 with the objects they refer to.

The objects are in the heap. The literal "Aman" is in the string pool subdivision of the heap.

The variables, being static, are in the class.


Since JVM allocates memory to static variable type in Method Area.

Yes you are right, as static variables are class level variable since they are part of the reflection data (class related data, not instance related) they are stored in the PermGenSpace > Method Area section of the heap,

But when it comes to static String type does it refer to heap area from method area or it provides memory in Method Area there itself.

See objects always get memory to heap area only no matter what, but yes static reference variables will be stored in Method Area.

Coming to your code,

static String s1 = new String("Aman");

Above line of code will create two objects 1st object through new keyword and 2nd objects through string literal "Aman" in the heap memory but remember the string literal will be stored in StringConstantPool and refer 2nd object in the heap from StringConstantPool and after that you are assigning the reference of objects which is in the heap to reference variable which is exists in MethodArea.

static String s2 = "Aman";

Now when compiler executes above line it will check "Aman" is already in the StringConstantPool it will not create another object instead it will return the same object which is already in the heap memory to static reference s2 which is in the Method Area.

I hope it will help.

链接地址: http://www.djcxy.com/p/82604.html

上一篇: 黄瓜:如何组织一个复杂的测试集

下一篇: JVM如何为静态字符串变量分配内存?