String s = new string (“XXX”); how many objects are created?

Time:2022-5-27

introduction

I went to the interview on Friday and was asked a dumb question

Interviewer: String s = new string (“XXX”); How many objects were created?
Me: two?
Interviewer: which two?
I:… (mute)

Before that, I only knew that there were two. As for why there were two, I didn’t know.

analysis

//In constant pool
String str1 = "abc";
 //On the heap
String str2 = new String("abc");

When direct assignment is performed, the string “ABC” will be stored in the constant pool with only one copy. At this time, the assignment operation is equal to creating 0 or 1 objects. If “ABC” already exists in the constant pool, the object will not be created, and the reference address will be directly assigned to STR1; If there is no “ABC” in the constant pool, create an object and assign the reference address to STR1.

Then, through new string (“ABC”); What is the form of? The answer is 1 or 2.

When the JVM encounters the above code, it will first retrieve whether “ABC” exists in the constant pool. If “ABC” does not exist, it will first create this string in the constant pool. Then execute the new operation. A string object storing “ABC” will be created in the heap memory, and the reference address of the object will be assigned to STR2. This procedure creates 2 objects.

Of course, if the corresponding string already exists when retrieving the constant pool, only a new string object will be created in the heap, and only one object will be created in this process.

When checking whether the constant pool has string constants of the same Unicode in the above procedure, the method used is the intern () method in string.

public native String intern();

Let’s take a look at the two storage modes of string in memory through a simple diagram.

String s = new string (

In the above diagram, we can see that the char value[] attribute of the string object created in the heap points to the char value[] in the constant pool.

As in the above example, we can also see the reference address of char value[] of string through the debug mode.

String s = new string (

The value values of the two string objects in the figure refer to {char[3]@1355}, that is, although they are two objects, their value values point to the same address in the constant pool. Of course, you can also compare the debug results when the string attribute (name) of a complex object (person) is the same, and the results are the same.

Advanced questions

If the interviewer says that the code of the program only has the following line, how many objects will be created?

new String("abc");

The answer is two?

Not really. The reason why this problem is listed separately is to remind you that there is no direct assignment operation (str= “ABC”), which does not mean that there is no “ABC” string in the constant pool. That is to say, whether there is a corresponding string in the constant pool when several objects are created depends not only on whether you create it, but also on whether other classes contain the string when the program is started.

More advanced questions

For the following example, we will not consider whether the corresponding string already exists in the constant pool, assuming that there is no corresponding string.

The following code creates several objects:

String str = "abc" + "def";

The above problem involves overloading “+” with string constants. When a string is spliced into a string by multiple string constants, it must be a string constant itself. The “+” sign of the string constant connects to the Java virtual opportunity, and optimizes it to the connected value during the program compilation.

For the above example, it has been merged into the “ABCDEF” string at compile time, so only one object will be created. Temporary string objects ABC and def are not created, which relieves pressure on garbage collector.

We can see the following by viewing the class file through javap.

String s = new string (

da2e53e424750afd4ec63dd5acbc6770.jpeg

To solve the above problem, let’s upgrade again. How many objects will the following code create?

String str = "abc" + new String("def");

Did you create 4, 5, or 6 objects?

Statement of four objects: there are “ABC” and “def” in the constant pool, and new string (“def”) and “ABCDEF” in the heap.

Is that right? Not exactly. If the above code creates several string objects, it can be said to be correct. However, the above code java virtual machine will also be optimized during compilation. A StringBuilder will be created to splice strings. The actual effect is similar:

String s = new String("def");
new StringBuilder().append("abc").append(s).toString();

Obviously, there is one more StringBuilder object, which should be five objects.

So what about creating six objects? Some students may think that the “ABCDEF” after the last tostring() of StringBuilder is not saved in the constant pool?

This is not saved yet. Let’s take a look at this Code:

@Test
public void testString3() {
    String s1 = "abc";
    String s2 = new String("def");
    String s3 = s1 + s2;
    String s4 = "abcdef";
    System.out.println(s3==s4); // false
}
String s = new string (

adc020264de49d273648164d40fed2d0.jpeg

Obviously, S3 and S4 have the same value, but the address of the value value is not the same. Even if the positions of S3 and S4 are adjusted, the effect is the same. S4 clearly exists in the constant pool. Where is the value corresponding to S3 stored? Obviously in the heap object.

Let’s take a look at how the tostring() method of StringBuilder converts the splicing result into a string:

@Override
public String toString() {
    // Create a copy, don't share the array
    return new String(value, 0, count);
}

Obviously, a new string object is created in the toString method, and the string object is created by passing the construction method of the array:

public String(char value[], int offset, int count) 

That is, the value of the string object directly points to an existing array, but does not point to the string in the constant pool.

Therefore, the exact answer above should be to create four string objects and one StringBuilder object.

expand

Interviewer: what is the difference between StringBuilder and StringBuffer?
Me: StringBuilder is not thread safe. StringBuffer is thread safe
Interviewer: where is the insecurity of StringBuilder?
I:… (mute) so, you know what? You can communicate in the comment area