下面的代码中,字符串其实并没有变,变的只是s的指向。
// 字符串不可变
public class Main {
public static void main(String[] args) {
String s = "hello";
System.out.println(s); // 显示 hello
s = "world";
System.out.println(s); // 显示 world
}
}
以及这段代码中,输出的是hello,因为从s = "hello" 开辟了hello这个字符串的空间,还有s指向了hello这个字符串;t=s,s是个指针指向的是字符串,所以t也指向hello,那么当s被赋值为world时,s的指针指向了world字符串,并不影响原先的t指针,所以打印t依旧是hello。
// 字符串不可变
public class Main {
public static void main(String[] args) {
String s = "hello";
String t = s;
s = "world";
System.out.println(t); // t是"hello"还是"world"?
}
}