You may ask a person if the string is variable? Presumably they would all say the same. The string is immutable, because the string is final decorated, and it is the final modified char[] array at the bottom.
You can see the string source code:
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[];
So the string is not to become, but we ignore the reflection, using reflection we can change the value of the string, say not much about how reflection is done:
public static void main(String[] args) throws Exception { // 创建字符串"Hello World", 并赋给引用s String s = "Hello World"; //把这个s保存一份用于对比 String temp = s; System.out.println("s和temp是否相等? " + s.equals(temp)); System.out.println("s = " + s); // Hello World // 获取String类中的value字段 Field valueFieldOfString = String.class.getDeclaredField("value"); // 改变value属性的访问权限 valueFieldOfString.setAccessible(true); // 获取s对象上的value属性的值 char[] value = (char[]) valueFieldOfString.get(s); // 改变value所引用的数组中的第5个字符 value[5] = '_'; System.out.println("s = " + s); // Hello_World System.out.println("s和temp是否相等? " + s.equals(temp)); }
We can see that we have used reflection to bypass the private permissions and modified the char[] array at the bottom of the string, and I want to read the little partner of this article. Do you know what to say when someone asks if the string is mutable?