String,stringbuffer, what is the difference between StringBuilder? Why is a string immutable?

Source: Internet
Author: User
Tags stringbuffer

This content is I reprint from everywhere to collate, is my study notes, if involves the copyright question, please give me the message.

Or the content of the wrong place, also please great God can help me to point out changes, thank you.


One, the difference

1. String is a literal constant, while StringBuffer and StringBuilder are string variables. Character content created by string is immutable, and character content created by StringBuffer and Stringbuidler can be changed.

2, StringBuffer is thread-safe, and StringBuilder is not thread-safe. StringBuilder is a single-threaded equivalence class that is added to the StringBuffer class, starting with JDK 5. We should give priority to using StringBuilder when we use it, because it supports all the operations of StringBuffer, but because it does not perform synchronization, it does not lead to additional system consumption due to thread security, so it is faster.


second, why the string is not variable

Although string, StringBuffer, and StringBuilder are final classes, the objects they generate are immutable, and they are internally all implemented by a char array, but the difference is that The char array defined in the String class is final, and StringBuffer and StringBuilder are inherited from the Abstractstringbuilder class, and their internal implementations are done by this parent class, The char array defined in this parent class is simply a private variable and can be appended with append. Because Abstractstringbuilder implements the Appendable interface.


Iii. Why string should be designed to be immutable

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.

[Java] view plain copy String S1 = "ABCD";   String s2 = "ABCD"; The schematic diagram looks like this:

Figure 1

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?

[JavaScript] view plain copy 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:

[JavaScript] view plain copy private int hash;//is used to cache Hashcode 3. Security
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:

[JavaScript] View Plain Copy boolean connect (string s) {if (!issecure (s)) {throw new SecurityException    ();   //If a string can be modified elsewhere, this will cause various 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.


Iv. Benefits of String type 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.

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.