No. Because string is designed as an immutable class, all its objects are immutable objects. In this Code, s originally points to a string object and the content is
"Hello", and then we perform the + operation on S. Does the object pointed to by s change? The answer is no. In this case, s points to another object instead of the original object.
String object with the content "Hello world! ", The original object still exists in the memory, but the reference variable s no longer points to it.
Through the above description, we can easily draw another conclusion, if you often make various modifications to the string, or make unforeseen modifications, therefore, using string to represent strings will cause a large memory overhead. Because the string object cannot be changed after it is created, a string object is required for each different string. In this case, you should consider using the stringbuffer class, which allows modification, instead of generating a new object for each different string. In addition, the conversion between the two types of objects is very easy.
At the same time, we can also know that if you want to use a string with the same content, you do not have to create a new string each time. For example, we need to initialize a string reference variable named S in the constructor and set it as the initial value. We should do this:
Public class demo {
Private string S;
...
Public demo {
S = "Initial Value ";
}
...
}
Rather
S = new string ("Initial Value ");
The latter calls the constructor every time to generate a new object, which has low performance and high memory overhead and has no significance. Because the string object cannot be changed, for strings with the same content, it can be expressed as long as a string object. That is to say, the constructor above is called multiple times to create multiple objects, and their string type attribute s points to the same object.
The above conclusion is based on the fact that for string constants, if the content is the same, Java considers them to represent the same string object. Using the new keyword to call the constructor always creates a new object, regardless of whether the content is the same or not.
The reason for designing a string class as an immutable class is determined by its purpose. In fact, classes in many java standard library are not variable. When developing a system, we sometimes need to design immutable classes to pass a set of related values, which is also the embodiment of Object-oriented thinking. The immutable class has some advantages. For example, because its object is read-only, concurrent multi-thread access will not have any problems. Of course, there are also some shortcomings. For example, each State must be represented by an object, which may cause performance problems. Therefore, the java standard library also provides a variable version, that is
Stringbuffer.