String 不可变的理解
- String 类是被 final 修饰的,不能被继承;
- 在用 “+” 号连接字符串的时候会创建新的字符串;
- String s = new String(“Hello world”); 可能创建两个对象,也可能创建一个对象。如果静态区中有 “Hello world” 字符串常量对象的话,则仅仅在堆中创建一个对象;若无此对象,则堆上和静态区中都需要创建对象。
- 在Java中,通过使用 “+” 符号来窗帘字符串的时候,实际上底层会转成通过 StringBuilder 实例的 append() 方法来实现。
通过一个例子来说明:
public class Example {
String str = new String("good");
char[] ch = {'a', 'b', 'c'};
public static void main(String args[]) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
}
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'g';
}
}
A good and abc
B good and gbc
C test ok and abc
D test ok and gbc
正确答案:B
理解:因为str的类型是String,String的值是不能修改的,所谓的修改只会新创建新的String,而ex.str依然指向原来的String地址,所以它的值没有改变,依旧是“good”。
补充:
public class Test {
public static void main(String[] args) {
String str = "Hello";
str += "World";
System.out.println(str);
}
}
输出:
上面的代码虽然修改了String对象的内容,但是还是能够正常运行。
理解:String类对象内容不能修改,但并不代表其引用不能改变。
String对象内容的改变实际上是通过内存地址“断开-连接”变化来完成的,str只是由原来指向"hello"变为指向“hello world”而已,而其原来的指向内容,是没有改变的。