Difference:
Direct assignment: only a heap memory space will be opened, and the string object can be automatically saved in the object pool. for next time use.
Construction method: Two heap memory spaces will be opened, one of which will become a garbage space and will not be automatically saved in the object pool. You can use the intern() method to manually enter the pool.
Recommended java related video tutorials: java video tutorials
Direct assignment:
Constant optimization mechanism:
The design of the String class uses the shared design pattern.
At the bottom of the JVM, an object pool (string object pool) will actually be automatically maintained. If the direct assignment mode is now used to instantiate the object of the String class, then the instantiated object (string content ) will be automatically saved to this object pool.
If you continue to use the direct assignment mode to declare a String class object next time, if there is specified content in the object pool, it will be directly referenced;
If not, a new string will be created. The object is then stored in the object pool for next use. The so-called object pool is an array of objects (the purpose is to reduce overhead)
Constructor method assignment:
It is standard practice for class objects to be instantiated using constructors.
String str = new String("hello");
Through analysis, it can be seen that if the String construction method is used, two heap memory spaces will be opened, and one of the heap memory will become garbage space. In addition to this shortcoming, there are also problems with string sharing.
Therefore, direct assignment is generally adopted.
Recommended related articles and tutorials: Getting started with java
The above is the detailed content of The difference between two types of object instantiation in Java's String class. For more information, please follow other related articles on the PHP Chinese website!