Why does Java design string immutable (immutable)

Source: Internet
Author: User

In Java, strings are string constants that can be analyzed in terms of memory, synchronization mechanism, data structure, etc.

  1: Need for constant pool in string

The place where a string differs from the common base variable type is the object. String objects in Java are stored in a string constant pool, and when you create a string, you first look for the same string object from the constant pool, and the new string object is created without being present.

If the string is designed to be mutable, there is a potential risk of affecting the other same object that points to the constant pool while modifying a string.

  2:hashcode Cache

In a hashmap or hashset data structure, storing a string is often a hash value, and a string immutable feature guarantees the uniqueness of the hash and avoids a hash-causing conflict. It is also not necessary to repeatedly compute the hash value every time a string object in the collection is used, high efficiency.

  3: Thread Safety

The immutability of string refers to the ability to share after different threads, while ensuring thread safety and helping developers reduce thread synchronization.

Of course, different scenarios can have different characteristics.

Why does Java design string immutable (immutable)

Related Article

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.