Why is java String an immutable type

Why is java String an immutable type

Easy- to-understand link: blog.csdn.net/u013905744/...

  • String objects are cached in the string pool, so these cached strings can be accessed by multiple clients. If one client's access affects the behavior of other clients, there is a risk. For example, if a client changes "test" to "TEST", all other clients will be affected accordingly. The reason why String is cached is for performance reasons. Therefore, this risk can only be avoided by setting the String to be immutable. At the same time, the String class is declared final. It is to prevent others from inheriting the String class and overriding the method of the parent class, which will destroy the immutability and cacheability of String and the calculation method of hascode.

  • Another reason why String is immutable is due to HashMap. Since HashMap is based on hash rules, only if the same object has the same hash value can it run well. And it is very popular to use String as the key value of HashMap. If String is variable, different Hash values will be generated. Only String is immutable, and the value stored in HashMap can be retrieved.

  • String is widely used as a parameter of Java classes. For example, you can open a network connection by taking the string of ip and port as parameters. You can open a database connection by taking the string of URL as a parameter. You can pass a file name. The string is used as a parameter to open a file through the Java I/O class. In these examples, if the String is variable, it will cause a serious security threat. Others can maliciously modify the cached characters to access all the files that you have authorized. By designing String to be immutable, such threats are avoided.

  • For multithreading, due to the immutability of String, you can safely share String among multiple important threads without causing thread synchronization problems.

  • Another important reason is that the immutability of String provides a fundamental guarantee for the safety of Java's class loading mechanism. If the String is variable, a request to load the "java.io.Writer" class can be changed to "mil.vogoon.DiskErasingWriter", so that security is not guaranteed.

How to implement an immutable class: blog.csdn.net/ksjay_1943/...