search
HomeJavajavaTutorialDetailed introduction to String strings in Java

Detailed introduction to String strings in Java

Aug 11, 2017 am 09:45 AM
javastringstring

The following editor will bring you an old-fashioned talk about Java String strings (a must-read article). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

There are two forms of string object creation in Java. One is the literal form, such as String str = "hello";, and the other is to use the new standard. Methods for constructing objects, such as String str = new String("hello");

I won't go into details about this common sense.

First of all, the String class is a final class. Why is it defined in final form?

To put it simply, for such frequently used data types, designers believe that the design is good enough and does not need to be inherited. Otherwise, random inheritance and overwriting may reduce the performance of data types. Program performance.

As the title says, since we are in-depth, let’s dig into the small actions of String at the jvm level.

First explain the form of literal creation:

When a literal form appears in the code to create a string object, the JVM will first The literal is checked, and if there is a reference to a string object with the same content in the string constant pool, this reference is returned. Otherwise, a new string object is created, and then the reference is put into the string constant pool and returned. Quote.

As shown below:


String str1 = "hello" ;

When we first created it, we thought that no object with the content hello existed. The JVM cannot find the existence of a string object with the content hello through the string constant pool, then it will create the string object, then put the reference of the newly created object into the string constant pool, and return the reference to the variable str1

If there is such a piece of code next


String str2 = "hello" ;

Similarly, the JVM still needs to detect this literal. The JVM searches for string constants Pool, it is found that the string object with the content "hello" exists, so the reference of the existing string object is returned to the variable str2. Note that a new string object is not recreated here.

Verify whether str1 and str2 point to the same object, we can use this code


System.out.println(str1 == str2);

The result is true.

The second type is created using new:


##

String str3 = new String("hello");

When we use new to When constructing a string object, a new string object will be created regardless of whether there is a reference to an object with the same content in the string constant pool. So we use the following code to test it,


String str3 = new String("hello");
System.out.println(str1 == str3);

The result is false. Indicates that these two references point to different objects.

intern

For the string object created using new above, if you want to add the reference of this object to the string constant pool, you can Use intern method.

After calling intern, first check whether there is a reference to the object in the string constant pool. If it exists, return the reference to the variable. Otherwise, add the reference and return it to the variable.


String str4 = str3.intern();
System.out.println(str4 == str1);

The result is true.

Difficult questions

Prerequisites?

The prerequisite for the implementation of the string constant pool is that the String object in Java is immutable, which can safely ensure that multiple variables share the same object. If the String object in Java is mutable and a reference operation changes the value of the object, other variables will also be affected. Obviously this is unreasonable.

Reference or object

The reference or object stored in the string constant pool is the most common problem. The string constant pool stores object references, not objects. In Java, objects are created in heap memory. The string constant pool exists in the permanent generation in the heap memory

Advantages and Disadvantages

The advantage of the string constant pool is to reduce the number of strings with the same content creation to save memory space.

If we insist on talking about the disadvantages, it is sacrificing CPU computing time in exchange for space. The CPU calculation time is mainly used to find whether there is a reference to an object with the same content in the string constant pool. However, its internal implementation is HashTable, so the calculation cost is low.

GC recycling?

Because the string constant pool holds references to shared string objects, does this mean that these objects cannot be recycled?

First of all, the objects shared in the question are generally relatively small. As far as I know, this problem did exist in earlier versions, but with the introduction of weak references, this problem should be gone now.

intern use?

关于使用intern的前提就是你清楚自己确实需要使用。比如,我们这里有一份上百万的记录,其中记录的某个值多次为美国加利福尼亚州,我们不想创建上百万条这样的字符串对象,我们可以使用intern只在内存中保留一份即可。

总有例外?

你知道下面的代码,会创建几个字符串对象,在字符串常量池中保存几个引用么?


String test = "a" + "b" + "c";

答案是只创建了一个对象,在常量池中也只保存一个引用。我们使用javap反编译看一下即可得知。

实际上在编译期间,已经将这三个字面量合成了一个。这样做实际上是一种优化,避免了创建多余的字符串对象,也没有发生字符串拼接问题。

The above is the detailed content of Detailed introduction to String strings in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment