Why is the string class not mutable in Java?

Source: Internet
Author: User

In the interview often encountered such a problem: 1, what is immutable object. What are the benefits of immutable objects. In what scenarios to use it, or more specifically, why should the Java String class be set to immutable types?

1, immutable objects, as the name implies is created after the object can not be changed, the typical example has a string type in Java.

2. Immutable objects have many advantages over mutable objects:

(1) Immutable objects can improve the efficiency and security of string pool (a constant pool of strings). If you know that an object is immutable, then you need to copy the contents of the object without copying it itself two is only to copy its address, copy the address (usually a pointer size) requires very little memory, the efficiency is very good. Two other variables that reference the same object are not affected.

(2) Immutable objects are safe for multithreading, because in the case of multi-threaded colleagues, the value of a mutable object is likely to be changed by other threads, which can result in unpredictable results. People use immutable objects to prevent this from happening.

The reason why Java sets string to be the most immutable is efficiency and security.

So how does an immutable type actually come true?

Taking into account a variety of factors in Java, need to integrate into memory, data structure and security considerations, in the following, I will do a summary for various reasons.

1, the need for string constant pool

A string constant pool is a special storage area in Java heap memory, and when a string object is created, if the string value already exists in the constant pool, a new object is not created, but the object that already exists is referenced.

The code is as follows:

String S1 = "ABC";

String s2 = "ABC";

In Java memory is divided into heap memory and stack memory, heap memory is the object, stack memory storage object reference, the string "ABC" is stored in the heap memory, and S1,S2 as the object reference is stored in the stack memory, the principle is as follows:

Heap Memory Stacks memory

String Object "ABC" ___ S1 a reference to a string variable

|______ S2

Assuming that the string object allows for changes, it will result in various logic errors. Changing one object, for example, affects another independent object.

Think about it: do S1 and S2 also point to the same object for a bit?

String S1 = "AB" + "C";

String s2 = "A" + "BC";

Many novices may feel that they are not pointing to the same object, but they will point to the same object in the constant pool, given that the modern compiler does the usual optimizations.

2. Run the string object cache Hashcode

Hash codes for string objects in Java are used frequently, such as in hashmap containers.

String invariance guarantees the uniqueness of the hash code, so it can be safely cached, which is also a performance optimization means that you do not have to compute a new hash code every time, in the definition of the string class has the following code:

private int hash;//is used to cache hashcode

3. Security

String is used by many Java classes (libraries) as parameters, such as network connection address URL, file path, path,

There are the string parameters required by the reflection mechanism, etc., if the string is not fixed, it will cause a variety of security risks.

In general, the reasons for the immutable string include design considerations, efficiency optimization issues, and security in the three main areas.

In fact, this is also the answer to many "why" in the Java interview.

4. The immutable benefits of the String class

String is one of the most commonly used classes in all languages. We know that in Java, string is immutable and final. Java also saves a string pool at run time, which makes string a special class.

The benefits of the non-variability of the string class

1. String pooling 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, multiple identical strings are not saved.) ), because if the variable changes its value, then

The values of other variables that point to this value will also change.

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 a string to obtain a connection to the database, or in socket programming, the hostname and port are

In the form of a string of characters. 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 the string is 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.

4. 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

Unknowable destruction.

5. 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 HashMap.

The keys in a string are often used.

Second, since it is known that the value of the immutable type of string and the role of such a large, then do not need a mutable type?

Of course not, when you need to insert or modify a string, the sting immutable type looks like an elbow, and a variable string type is required: StringBuffer.

StringBuffer, like string, represents a string, but because StringBuffer is implemented internally in a different way than string, StringBuffer is handling strings

Do not produce new objects in memory usage because of the string class.

Why is the string class not mutable in Java?

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.