“This is the fifth day of my participation in the August More Text Challenge.

Last time we talked about strings being shared, so how does that work? That’s the focus of this episode: string constant pools

String constant pool

To reduce the number of string objects that Java programmers often use, the JVM optimizes memory by creating a special section of the Heap for string constants, called the string constant pool.

We know that there are many different ways to create string objects. Which way should strings be added to the constant pool?

The answer is only String STR = “ABC”, which is created using double quotes.

Let’s start with an interview question:

String str1 = new String("abc");
Copy the code

How many objects did the above line of code create? The answer is two.

One is that the "ABC" created in double quotes is stored in the constant pool. The other is that the object that comes out of new is stored in the heap.Copy the code

If it’s not clear by now, let’s look at the next common example:

String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str2 == str3);
Copy the code

As you can see,str1 is str2, and str1 and str2 are not str3. As you can see above, strings created using double quotes are stored in the constant pool. forString str1 = "abc";The JVM first looks for a string equal to “ABC” in the constant pool, and creates the string in the constant pool if it doesn’t. forString str2 = "abc";, so the JVM references “ABC” to STR2, so str1 and STR2 have the same reference. Obviously the first result is true, no problem. Strings created with new are stored in the heap and therefore do not have the same reference.

Consider the following example:

String str4 = "a";
String str5 = "b";
String str6 = "ab";
String str7 = str4 + str5;
String str8 = "a" + "b";
System.out.println(str6 == str7);
System.out.println(str7 == str8);
System.out.println(str6 == str8);
Copy the code

As you can see from this example, when str8 is created, “A” and “B” do not exist. The result is “AB”. Objects created using string concatenators containing variables are stored in the heap, as in STR7.

Conclusion:

1 String objects created with "" double quotes are stored in the constant pool. Strings created using string concatenation are stored in the constant pool, and string objects created using new are stored in the heap. 4 String objects created using contain variables are also stored in the heap. (It is important to note here that variables decorated with final are equivalent to constants.)Copy the code