Home Java javaTutorial Detailed introduction to String strings in Java

Detailed introduction to String strings in Java

Aug 11, 2017 am 09:45 AM
java string string

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

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

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

The result is true.

The second type is created using new:


##

String str3 = new String("hello");
Copy after login

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

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

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

答案是只创建了一个对象,在常量池中也只保存一个引用。我们使用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 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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles