1. Noun interpretation
Stack : An area allocated by the JVM to hold actions and data references that are executed by the thread. The stack is a running unit, and a thread in Java will have a line stacks corresponding to it.
Heap : An area allocated by the JVM for storing data such as objects.
constant Pool : In the compile phase, a chunk of storage allocated in the heap to store an explicit string,float or integer. For example, String str= "abc"; The ABC string is explicitly declared, so it is stored in a constant pool.
2. Look at this example, using jdk5+junit4.5 to write an example that completely passes the test
ImportStaticOrg.junit.Assert.assertNotSame;
ImportStaticOrg.junit.Assert.assertSame;
ImportOrg.junit.Test;
PublicClassstringtest{
@Test
PublicvoidTestTheSameReference1 () {
String str1="Abc";
String str2="Abc";
String STR3="Ab"+"C";
String STR4=NewString (STR2);
str1 and str2 refer to the same string object from the constant pool
Assertsame (STR1,STR2);
//STR3 by compiling optimizations, referencing from the same object as str1
Assertsame (STR1,STR3);
//STR4 because it is another object that is redistributed in the heap, its reference differs from STR1
Assertnotsame (STR1,STR4);
}
}
- The first assertion is well understood, because "abc" is stored in a constant pool at compile time, and references to both STR1 and STR2 are "ABC" in the Constant pool. so the str1 and str2 references are the same.
- The second assertion is that because the compiler is optimized, the compiler will first stitch the string, and then look in the constant pool for the existence of the string, and if so, let the variable refer directly to the string. so the str1 and STR3 references are the same.
- The STR4 object is not explicitly assigned, and the compiler will reassign a zone in the heap to store its object data. so the quotes of str1 and STR4 are not the same.
Stacks of Java memory and constant pools