Java String class why is immutable _java

Source: Internet
Author: User

Answer one:

One of the most popular Java face questions is: What are immutable objects (immutable object), what are the benefits of immutable objects, what should be used, or more specifically, why should Java string classes be set to immutable types?
Immutable objects, as their name suggests, are objects that cannot be changed after creation, and the typical example is the string class in Java.

Copy Code code as follows:

String s = "ABC";
S.tolowercase ();

As S.tolowercase () does not change the value of "ABC", It creates a new string class "abc" and then points the new instance to the variable S.
Invariant objects have many advantages over mutable objects:
1. Immutable objects can improve the efficiency and security of string pool. If you know that an object is immutable, then you need to copy the object's content without duplicating its own and simply copying its address, and copying the address (usually the size of a pointer) requires very little memory efficiency. There is also no effect on other variables that refer to this "ABC" at the same time.
2. Immutable objects are safe for multithreading, because the value of a mutable object is likely to be changed by other processes while multithreading is in progress, which can result in unpredictable results, which may be avoided by using immutable objects.
There are other reasons, of course, but the biggest reason Java can set a string to immutable is efficiency and security.


Answer two:

It's a cliché topic (this is the old yet still popular question). In Java, designing a string to be immutable is the result of taking into account a variety of factors, and to understand the problem requires comprehensive memory, synchronization, data structure, and security considerations. In the following, I will make a summary for a variety of reasons.

1. The need for a string constant pool

String Chang (String pool, string intern pool, string reserved pool) is a special storage area in the 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. Instead, it references an object that already exists.
As shown in the following code, only one actual string object will be created in heap memory.

Copy Code code as follows:

String S1 = "ABCD";
String s2 = "ABCD";

The schematic diagram looks like this:

If a string object allows a change, it can cause a variety of logical errors, such as changing an object to affect another independent object. Strictly speaking, the idea of this constant pool is an optimization method.

Think: If the code looks like this, will S1 and S2 also point to the same actual string object?

Copy Code code as follows:

String s1= "AB" + "CD";
String s2= "abc" + "D";

This may be a violation of novice intuition, but given the conventional optimizations that modern compilers make, they all point to the same object in a constant pool. Alternatively, you can view the compiled class file with tools such as Jd-gui.

2. Allow string Object caching Hashcode

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

String invariance guarantees the uniqueness of the hash code, so it can be safely cached. This is also a performance optimization means that you don't have to compute the new hash code every time. The following code is in the definition of the string class:

Copy Code code as follows:

private int hash;//to cache hashcode

3. Safety

A string is used as a parameter by many Java classes (libraries), such as a network connection address URL, a file path path, and a string parameter required by the reflection mechanism, which can cause a variety of security risks if the string is not fixed.
If you have the following code:

Copy Code code as follows:

Boolean connect (string s) {
if (!issecure (s)) {
throw new SecurityException ();
}
If you can modify a string elsewhere, this will cause a variety of unexpected problems/errors
Causeproblem (s);
}

Overall, the reasons for string immutable include design considerations, efficiency optimization issues, and security in the three major areas. In fact, this is the answer to many of the "why" in a Java interview.


Answer three: The benefits of String class Immutability

A string is the most commonly used class in all languages. We know that in Java, string is immutable and final. Java also saves a string pool at runtime (string pool), which makes a string a special class.

The benefits of a string class immutability

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. However, if the string is mutable, then string interning will not be implemented (translator Note: string interning means to save only one for different strings, that is, not to save multiple identical strings.) Because then, if the variable changes its value, the value of other variables that point to that value will also change together.
2. If the string is mutable, it can cause serious security problems. For example, the database username and password are passed in as a string to obtain a connection to the database, or in socket programming, the hostname and port are passed in as strings. Because the string is immutable, its value is immutable, otherwise hackers can drill into a loophole, changing the value of the object the string points to, creating a security vulnerability.
3. Because the strings are immutable, they are multi-threaded and 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 class loader 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.
5. Because the string is immutable, the hashcode is cached when it is created and does not need to be recalculated. This makes the string suitable for the key in the map, and the string is processed faster than the other key objects. This is where the keys in HashMap tend to use strings.
The above is the benefit of the string immutability I've summed up.

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.