Java-11.1 unchanged strings
In this section, we will discuss the unchanged strings.
Why is it unchanged?
Let's first look at the String constructor.
public String() {this.offset = 0;this.count = 0;this.value = new char[0]; }
Here, let's look at the value:
/** The value is used for character storage. */ private final char value[];
The identifier of value is final. Therefore, the character string cannot be modified in the same place in the compiler.
package com.ray.ch11;public class Test {public static void main(String[] args) {String a = a;String b = a.toUpperCase();System.out.println(a == b);}}
Output:
False
In the conversion process, the string object "a" is actually copied and then converted.
We can click in the toUpperCase method, which has two notes:
System.arraycopy(value, offset, result, 0, firstUpper);
And
return new String(0, count+resultOffset, result);
The first sentence is to copy the input value, and the second sentence is in the last new string.
Then, you can search for return new String in the source code of the String class. You will find that the methods you commonly use basically return a new String.
Summary: here we simply end the unmodifiable features of the string. In fact, it contains a lot of content, but it is not detailed for the time being. We know that this feature is available.