What is an immutable object? As we all know, in Java, the string class is immutable. So what exactly is an immutable object? It can be said that if an object cannot change its state after it has been created, then the object is immutable. The inability to change the state means that the member variables within the object cannot be changed, that the value of the underlying data type cannot be changed, that a variable of the reference type cannot point to other objects, and that the state of the object to which the reference type points cannot be changed. Distinguishing between objects and objects for Java beginners, there is always doubt about string being an immutable object. Look at the following code: String s = "ABCABC"; System.out.println ("s =" + s); s = "123456"; System.out.println ("s =" + s); The result is: s = abcabc s = 123,456 First create a String object s, then the value of S is "ABCABC", then the value of S is "123456". As you can see from the printout, the value of S has indeed changed. So how do you say the string object is immutable? In fact, there is a misunderstanding: s is just a reference to a string object, not the object itself. An object is an area of memory in memory, and the more member variables, the greater the amount of space that the memory area occupies. A reference is just a 4-byte data that contains the address of the object it points to, and the object can be accessed by this address. That is, S is just a reference, it points to a specific object when s= "123456"; After this code was executed, a new object "123456" was created, and the reference S re-pointed to the object of the heart, the original object "Abcabc" still exists in memory, and has not changed. Why is the string object immutable? To understand the immutability of a string, first look at what member variables are in the string class. In JDK1.6, there are several member variables for string: Public final class string implements Java.io.Serializable, comparable
Why string in Java is immutable