The difference between two types of object instantiation in Java's String class

王林
Release: 2019-11-25 17:13:34
forward
2204 people have browsed it

The difference between two types of object instantiation in Java's String class

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:

The difference between two types of object instantiation in Javas String class

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");
Copy after login

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!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!