String can be said to be one of the most common words in Java, related to him or stringbuffer and Stringbuild, these two later, now talk about string is the string. Everything in Java is Object, and string is no exception. And the string in Java is immutable.
1. About string immutable I was just learning Java and I had a question.
String s = "AAA"; s= "BBB"// output BBB
The string s in this code is clearly changed, why is the string immutable. To explain here, this is a reference, not a change in the actual value in the heap memory. For example:
String s = "AAA"= S.replace ("A", "B"// output BBB// output AAA
Here you can see that the Replace method produces a new string, and the original string does not change. The following is an analysis of why a string object is immutable from the source perspective.
Public Final class String implements java.io.Serializable, comparable<string>, charsequence { /** */ privatefinalchar value[];}
Open the string source code, you can see that the string is a final class, indicating that it is not inheritable, the char array used to store the value is also the final type, indicating that it cannot be changed, but only final is not enough, because the final decorated array, although the reference can not be changed, but its own value is variable. For example: Final char value[] = {£ º}; VALUE[1] = 4; The value in the array becomes {1,4,3}. To prevent this, sun sets the string class to be non-inheritable, modifies it with private in front of the char array, and carefully writes all the methods of the string class to ensure that each method does not alter the value of the array.
All of the methods mentioned in the string class above have not changed the array values, which is explained in detail below.
Take the Replace method as an example
PublicString Replace (CharOldChar,CharNewchar) { if(OldChar! =Newchar) { intLen =value.length; inti =-1; Char[] val = value;/*avoid GetField opcode*/ while(++i <Len) { if(Val[i] = =OldChar) { Break; } } if(I <Len) { CharBuf[] =New Char[Len]; for(intj = 0; J < I; J + +) {Buf[j]=Val[j]; } while(I <Len) { Charc =Val[i]; Buf[i]= (c = = OldChar)?Newchar:c; I++; } return NewString (BUF,true); } } return This; }
--string of Java High-frequency words (parsing String objects from the source angle)