Java Fundamentals: String immutability and final retouching

Source: Internet
Author: User

Reprint Please specify source: Jiq Technical Blog-Jiyichin


Non-variability of string

Java specifies that the string is immutable (immutable). The fact that this immutable has two meanings:


1 content is not variable

no matter what seems to change their operation. is actually another new object.

string s = new string ("111"); String NewS = S;news = "DSFSD"; System.out.println (s);  111

Assume that the content cannot be immutable. When two references point to one memory at the same time, one of the changes also affects the other.


2 Implementation mode is not variable

Use String type variable, it cannot exhibit other behavior. This is why the string class needs tobe decorated with finalkeyword, and imagine that the string does not have to be final decorated. It can be inherited and overridden by the method:

/** * Simulates a non-final string * @author Jiyiqin * */class mystring{public char value[] = new CHAR[10];       Mystringtolowercase (MyString s) {System.out.println ("converts s to lowercase but does not change the original S");       Char newvalue[] = new Char[s.value.length];       for (int i = 0; i < s.value.length; i++) newvalue[i]= Lowerutils.lower (S.value[i]);       mystringnewstring = Newmystring ();       Newstring.value = newvalue;    return newstring; }}/** * Inherits MyString, toLowerCase rewrite it * @author jiyiqin * */class overridestring extends mystring{mystringtolowercase (My String s) {System.out.println ("Directly changes the memory passed in S.       Convert s to lowercase ");             for (int i = 0; i < s.value.length; i++) S.value[i] = Lowerutils.lower (S.value[i]);    return s; }} public Classfinalstringtest {/** * Test function, Java design string is immutable * So the string must be decorated as final. Otherwise its * once inherited. Similar to the following when called. The passed-in parameter is the subclass to which it is inherited.     The call is a method that is overridden, and this overridden method may break the immutable nature of the * string. * @param S * @return */static MyStringlowercusstring (MyString s)//polymorphic {return s.tolowercase (s);       } public static void Main (string[] args) {OVERRIDESTRINGSS = Newoverridestring ();    Lowercusstring (ss);//pass in the rewritten string Class Lowerutils.testfinalclass (); }}

Can see the Lowercusstring method wants is the MyString object, but its subclasses can be passed in and use, after the call to find the object passed in the content of the S is changed, showing different behavior with the parent Class!!

In the same way. The application is able to write a new string class, changing the Hascode method so that the content of the same string object returns a different hashcode, so that hashmap when using the string variable as key, it is found that the same content key is actually hashed to a different location.

In addition to the implementation method can not be changed this reason. Another advantage of modifying a string to final is efficiency.

String Other Features

In addition to the above-mentioned immutability. String also has the following characteristics:

Feature 1: Compile-time and execution-time differences

A string object that can be determined at compile time is put into a constant pool

You execute the ability to determine or new-out string objects are put into the heap


2:hascode Uniqueness of characteristics

Two contents the same string Object Hashcode return value must be the same

Here's a sample summary of these two features:

Final String tmp = "Ji"; Constant pool, compile-time determination string tmp2 = "Ji"; Constant pool, compile time determine  string s1 = "Jiyiqin";//Chang, compile-time determine      string s2 = "Jiyiqin";//Chang, compile-time OK string s3 = "Ji" + "yiqin";//Chang , compile-time determine string s4 = tmp + "Yiqin";  Constant pool, compile-time determination (final once initialization is immutable)  string s5 = tmp2 + "Yiqin",//heap, OK string at execution time s6 = new string ("Jiyiqin");//heap, execution time OK      System.out.println (S1.hashcode ()); System.out.println (S2.hashcode ()); System.out.println (S3.hashcode ()); System.out.println (S4.hashcode ()); System.out.println (S5.hashcode ()); System.out.println (S6.hashcode ()); All the same      System.out.println (S1 = = s2);//true. Point to the same memory System.out.println in the constant pool (S1 = = S3); True, pointing to the same memory System.out.println in the constant pool (S1 = = S4); True, pointing to the same memory System.out.println in the constant pool (S1 = = S5); False, a pointer to a heap pointing to the constant pool System.out.println (S1 = = S6); False, a pointer to a heap pointing to the constant pool System.out.println (S5 = = S6); False to point to a different area of memory in the heap

Double, Long, Integer

For the immutability of a string (including the content is immutable and the implementation is not variable), and Hashcode uniqueness, Double, Long, Integer is the same.

The difference is that they have no execution and compile-time differences, and are allocated memory on the heap.

Java Fundamentals: String immutability and final retouching

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.