字面量的字符串"aaa"
是在加载类时创建和池化的,所以当你的两行代码被执行时,只会创建一个新的字符串。
需要明确的是:这两个示例在执行时都只创建一个新的 String 对象。第一次使用包含字符串“aaa”的类时会创建文字。
class FooBar{
void foo(){
String s1 = "aaa";//the literal already exists
String s2 = new String("aaa");//creates string for s2
}
void bar(){
String s1 = new String("aaa"); //creates string for s1
String s2 = "aaa";//the literal already exists
}
}
class Test{
public void main(String... args){
...
//first time class FooBar used in program, class with literals loaded
FooBar fb = new FooBar();
//creates one string object, the literal is already loaded
fb.bar();
//also creates one string object, the literal is already loaded
fb.foo();
}
}