答案就是为了安全。
那么string的底层原理是什么样的?下面是源码
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0
很容易就看出来String就是由char类型的数组封装的,内部的成员变量都是private的,也没有提供set方法来修改这些值。
在String外部无法修改String,因为自己的变量是final修饰的,所以在String内部也不能改变。所以认为String对象是不可变的
但是用反射可以改变String对象,但是一般貌似不会这么做。