About the immutable string class in Java

Source: Internet
Author: User

Tag: Address design operation cannot data access style serial RAC

Here, the immutable string is no longer discussed, just to say why the string is immutable.

Rough point, straight to the, string of the immutable reason there are three:

1). The String class is final

A class with a final decoration cannot be inherited, and it is used in the string class to represent that it cannot be inherited, and it cannot be inherited by a later programmer and then modified by a new class. This trick, intended to let string "childlessness", I think and castration is similar to the wonderful.

2). The value of string is a char array, which is modified by the final and private

Paste the source of the string:

 1  public  final  class   String  2  implements  java.io.Serializable, Comparable<string> 3  /**   The value is used for character storage.  */ 4   Private  final  char   value[];  5   ...  6 } 

As you can see, the value of string actually exists in a private final char array, and the array is a reference variable, and giving it a final effect is to make the reference address of the handle of value immutable, but the array to which value points is placed in the heap heap, The value of this can be changed .

The purpose of the private adornment is to prevent value from being accessed by other classes, which prevents other classes from directly manipulating the data in the heap that the value reference points to.

3). The string designer avoids the direct manipulation of data in the heap in all subsequent methods

As mentioned in the 2nd, "value points to an array that is placed in the heap, and its value can be changed." Although value is final modified, it does not have much effect, and even final protection of value is less than private. The reason why we can't modify strings in our use is because Sun's programmers are carefully avoiding the direct manipulation of string content when designing a string.

About the immutable string class in Java

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.