Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does the immutability of Java string mean?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the meaning of the immutability of the Java string". In the daily operation, I believe that many people have doubts about the meaning of the immutability of the Java string. The editor consulted all kinds of materials and sorted out a simple and easy-to-use method of operation. I hope it will be helpful to answer the doubt of "what is the meaning of the immutability of the Java string?" Next, please follow the editor to study!

Preface

The String (string) object is the most frequently used and important object in Java development. It is used so frequently that String is constantly optimized at the implementation level, from Java6 to Java7 to the new implementation of Java9, to improve the performance of String objects, and what remains unchanged is the inherent feature of String: immutable. This article mainly talks about the immutability of String and why it exists.

What is the immutability of String

First, let's take a look at what an immutable object is: once the object is created and initialized, the internal state data remains unchanged. Looking at the String class in the JDK source code, you can see that the class itself is decorated by final, and most of the internal properties are decorated by final, except that the field hash is calculated and cached through the contents of the string. This behavior makes it impossible for the String class to be extended and the internal properties to be modified.

Then we will use the form of drawing to illustrate the immutability of String.

Usually we initialize the string in the following form:

The reference variable an of type String retains a reference to the string object string, as shown in the following figure, and the arrow represents the reference relationship between the variable an and the real String object.

With the above code, we assign the variable a to the variable b, which also stores a reference to the string object string, which points to the same object.

When we try to reassign variable a, let's see if it has any effect on variable b.

Presumably the partner will know at a glance that the printed result must be string2,string, and the reference relationship between these two variables and the string object is also shown by drawing.

After the variable an is re-assigned, the new reference is saved instead of directly changing the data on the original string object, while variable b still stores the reference of the object string, and the variables an and b are independent of each other and do not affect each other, which shows that the String object is immutable.

It may also be a little confusing to recognize the little friends of Java here: assign a value string to a String object, and then let a value be string2, at this time the value of a becomes string2, the value of a changes, why do you say that the String object is immutable?

In fact, the problem is also very simple, here an only stores a reference to the String object, not the object itself, a stores an address reference to the memory where the object is located, when the second assignment, a reference points to the memory address of the object string2, while the object string2 is recreated, the previous string object is still in memory and is referenced by the variable b.

In addition, the method of the String class that returns the String object does not change itself, but returns a new String object to implement, such as concat,replace,substring, and so on.

Why String needs to be immutable

After talking about what String is immutable, let's talk about why String needs to be immutable and what are the benefits?

Implementation of string constant Pool

In Java, we usually have two ways to create string objects, one is to create string objects literally, as in the code above, and the other is to create string objects through new, such as String c = new String ("string 3"). The difference between the two is that when the string is created literally, JVM will now check whether the string content already exists in the string pool, and if it exists, it will directly return the corresponding reference instead of re-allocating memory to create it. If it does not exist, the string data will be cached in the string pool for reuse. It is precisely because strings are immutable that the same string content allows JVM to reduce additional memory allocation operations and use string objects directly in the string pool, which is good for performance improvement and memory savings.

With regard to string pooling, here is a brief introduction: * * Java's string pool belongs to a special memory area specified by JVM and is used to store string literals. * * before Java7, the string pool is assigned to the method zone of JVM and is part of the constant pool. After Java7, the string pool is moved to heap memory for management. The advantage is that the JVM allows garbage collection operation to reclaim the memory occupied by unreferenced strings, thus saving memory.

Hashcode caching

String, as the basic data structure, is widely used in some collection containers, especially in some hash sets. In hash sets, the location of elements is determined according to the object's hashCode () method. Because the string hashcode attribute will not be changed, the uniqueness is guaranteed, so that containers such as HashMap,HashSet can achieve the corresponding caching function. Because of the immutability of String, to avoid double computing hashcode, only cached hashcode can be used, which greatly improves the performance of using String objects in hash sets.

Thread safety

In multithreading, only immutable objects and values are thread-safe and data can be shared across multiple threads. Because String is naturally immutable, when a thread "modifies" the value of a string, it will only produce a new string object without side effects on the access of other threads, accessing the same string data without any synchronization operation.

Security.

Since strings are widely used in any Java system and will be used to store sensitive information, such as accounts, passwords, network paths, file processing and other scenarios, it is particularly important to ensure the security of the string String class. If the string is variable and easy to be tampered with, then we can not guarantee that it is secure when using strings, and it is likely to occur SQL injection, access to dangerous files and other operations.

Conclusion

Through this article, we introduce that String are immutable, and their references can be used as a common variable. No matter passing them between methods or threads, there is no need to worry about the change of the actual String object it points to, and the immutable features also bring a lot of benefits at the language level and program level. In ordinary programming practice, we should also learn to emulate and use James Gosling. The father of Java said, "I will use immutable objects as much as possible."

At this point, the study of "what is the meaning of immutability of Java strings" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report