String A = new string ("ABC ");
String B = "ABC ";
String c = new string ("ABC ");
Question: A String object is created in total?
Understanding about the string pool:
String A = new string ("ABC"); how many objects are created in total? 2
Running sequence:
1. Because it is a new string (), we need to create a new space in the heap.
2. Search for objects with the same value as ABC in the pool. Because no, create an ABC object in the pool!
3. Copy the objects in the pool to the heap, create an object in the heap, and return the reference address of the heap to A. A is not an object,
Only the returned address variables are stored.
String B = "ABC"; no zero objects are created
First, this expression does not use the New Keyword, so it does not open up space in the heap, but directly de-Words
Search for keys with the same data in the string pool. If yes, return the reference address of this key,
Two strings point to the address of the string pool! If not, create an object directly in the string pool! And
Return address. This creates a String object that is irrelevant to the heap zone!
String c = new string ("ABC"); an object is created this time! 1
First, find this value in the string pool. If no value exists, create it because it is already in
The object is created in the string pool.
New String () and copy this object to create a new object in the heap!
Therefore, you can create an object in the string pool instead of directly creating an object in the heap! Institute
It is!
String d = B + "ABC"; there is a string reference at this time, so create a space in the heap and save the value,
Summary: when creating a string, you must first search for it in the string pool. If not, create a string, as shown in figure
If yes, do not create it!