Here's a bunch of examples to illustrate the immutability of Java's string.
1. Declare a string
s = "abcd";
The s variable holds a reference to the string object, and the following arrows explain the reference to which object is saved.
2. Assign a string variable to another string variable.
s;
The string object cannot be changed to show 2 variables s2 Save the same referenced values, which point to the value of the same object.
3. connect string
s = s.concat("ef");
The variable s now holds a reference to the newly created Sting object.
Summarize:
Once a string is created in memory (heap), it cannot be changed. We should note that all the string methods do not change the string itself, but instead return a new string.
If we need a string that can be changed, then we can use StringBuffer (Translator Note: thread safe) or StringBuilder. Otherwise, every time a new string is created, it wastes a lot of garbage collection.
Here is an example of a StringBuilder application.
PublicStatic String readfiletostring ()Throws IOException {File dirs =New File ("."); String FilePath = Dirs.getcanonicalpath () + file.separator+"SRC" +file.separator+"Testread.java"; StringBuilder FileData =new StringBuilder (1000); new bufferedreader (new filereader (FilePath)); char[] buf = new char[1024] ; int numread = 0; while ((Numread = Reader.read (BUF))! =-1) {String readdata = string.valueof (BUF, 0, numread); Filedata.append (readdata); buf = new char[1024];} reader.close (); String returnstr = filedata.tostring (); System.out.println (RETURNSTR); return returnstr;}
I. Illustration of string immutability in Java