On the difference between two assignment methods of string in Java
Similar to ordinary objects, create string objects through new. String str = new String("Hello"); The memory diagram is shown in the following figure. The system will first create an anonymous object "hello" and store it in the heap memory (let's call it a for the time being). Then the new keyword will open up a new space in the heap memory, store "hello" and return the address to STR in the stack memory. At this time, object a becomes a garbage object because it is not pointed to by any variables in the stack, Will be automatically recycled by GC.
Direct assignment. For example, string STR = "hello"; First, you will find out whether there is a "hello" object in the buffer pool. If not, you will create a new one and enter it into the pool. Therefore, this assignment has an advantage. Next time, if there is a string object also defined as "hello" by direct assignment, you do not need to open up a new heap space, but still point to the "hello" in the pool
explain
L the content of the string is stored in the string constant pool in the method area. If it does not exist, it will be created. If it already exists, it will directly refer to the past.
L string STR1 = "AA", this is a direct operation string constant pool, which refers to the past; String str2 = new String(“AA”); This is to open up the object of this class in the heap space. In fact, it refers to the string constant pool internally;
test result
summary
The above is all about the difference between the two assignment methods of string in Java. I hope it will be helpful to you.