Why is the string class immutable?

Source: Internet
Author: User

Java saves a string pool at run time, which makes string a special class.

The benefits of the non-variability of the string class

(1) A string pool is possible only if the string is immutable. The implementation of a string pool can save a lot of heap space at run time, because different string variables point to the same string in the pool. But if the string is mutable, then string interning will not be implemented (translator Note: string interning refers to just one save for different strings, that is, not many of the same strings are saved.) Because then, if the variable changes its value, the value of the other variable that points to that value will change as well.

(2) If the string is mutable, it can cause serious security problems. For example, the user name and password of the database are passed in as strings to get a connection to the database, or in socket programming, the hostname and port are passed in as a string. Because the string is immutable, its value is immutable, otherwise hackers can drill into the empty, change the value of the object that the string points to, resulting in a security breach.

(3) Because strings are immutable, multithreading is secure, and the same string instance can be shared by multiple threads. This will not use synchronization because of thread-safety issues. The string itself is thread-safe.

The ClassLoader uses a string, and immutability provides security so that the correct class is loaded. For example, if you want to load the Java.sql.Connection class, and this value is changed to myhacked.connection, it will cause an unknown damage to your database.

(4) because the string is immutable, hashcode is cached when it is created and does not need to be recalculated. This makes the string well suited as a key in the map, and the string is processed faster than other key objects. This is where keys in hashmap tend to use strings.

Why is the string class immutable?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.