I. Illustration: the String in Java is non-mutable. javastring
Here are a bunch of examples to illustrate the immutable Java String.
1. Declare a String
String s = "abcd";
The s Variable saves the reference of the string object. The arrows below explain the reference of the object that is saved.
2. assign a value to a String variable to another String variable.
String s2 = s;
The String object is unchangeable. The 2 variable s2 stores the same referenced values, all of which point to the same object value.
3. Connect to String
s = s.concat("ef");
The variable s now stores references to the newly created sting object.
Summary:
Once a string is created in the memory (HEAP), it cannot be changed. We should note that all the String methods will not change a string, but return a new string.
If we need a string that can be changed, we can use StringBuffer or StringBuilder. Otherwise, a large amount of time is wasted on garbage collection every time a new string is created.
Here is an application example of StringBuilder.
public static String readFileToString() throws IOException { File dirs = new File("."); String filePath = dirs.getCanonicalPath() + File.separator+"src"+File.separator+"TestRead.java"; StringBuilder fileData = new StringBuilder(1000);//Constructs a string buffer with no characters in it and the specified initial capacity BufferedReader reader = 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; }