5.4 String

Source: Internet
Author: User

JAVA in Why String is a Immutable of the ?

1. Design : When creating a string (String str2 = "abc"), if it (originally a string str = "abc") already exists in the pool (in fact, the stack in memory), it will return a reference to the existing string, instead, How to create a new string and return the reference. If the string is not immutable, changing one of the references to a string will result in another reference to the wrong value.

2. efficiency : Allow string to cache its hashcode. The hashcode of string is used very frequently in Java. For example, in Hashmapzhong, a string designed to immutable ensures that hashcode is always the same, so hashcode can be cached without worrying about changes. In other words, it is more efficient to use hashcode every time you want to calculate it.

3. Security : String is widely used as a parameter by classes in Java, such as network connections, open files, and so on, if the string is not immutable, a connection or file changes will lead to serious security threats, one method thought is connected to a machine , and actually not. A mutable string will also cause a security problem with reflection because the parameters in the reflection are of type string.

Attached String , StringBuffer , StringBuilder

comparison of the three in the speed of execution: StringBuilder > StringBuffer > String

String: Strings constant stringbuffer: String variable StringBuilder: string variable

As can be seen from the above name, string is a constant, and StringBuffer and StringBuilder are not the same, they are string variables, is a variable object, whenever we use them in the operation of the string, is actually operated on an object, This will not create a number of objects like string to operate, of course, the speed is fast. Again,StringBuilder is thread- insecure, and StringBuffer is thread-safe, so StringBuilder is the fastest.

5.4 String

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.