关于String str = "abc"的内部工作。Java内部将此语句转化为以下几个步骤:
(1)先定义一个名为str的对String类的对象引用变量:String str;
(2)在栈中查找有没有存放值为"abc"的【地址】,如果没有,则开辟一个存放字面值为"abc"的地址,
接着创建一个新的String类的对象o,并将 o的字符串值指向这个地址,而且在栈中这个地址旁边记下这个引用的对象o。
如果已经有了值为"abc"的地址,则查找对象o,并返回o的地址。
(3)将str指向对象o的地址。
值得注意的是,一般String类中字符串值都是直接存值的。但像String str = "abc";这种场合下,
其字符串值却是保存了一个指向存在栈中数据的引用!
public class Test {
public static void changeStr(String str){
str = "welcome";
// 在栈中查找字面量值为 welcome 的变量, 将其地址赋给 str
// main 方法中的 str 存放的仍然是 hello world 的地址
System.out.println(str.hashCode()); // 1233099618
}
public static void main(String[] args) {
String str = "Hello world";
System.out.println(str.hashCode()); // -832992604
changeStr(str);
System.out.println(str.hashCode()); // -832992604
System.out.println(str);
}
}
=====================================
String s = "hello world";
System.out.println(s.hashCode()); // 1794106052
String ss = "hello world";
System.out.println(ss.hashCode()); // 1794106052
System.out.println(s == ss); // true
System.out.println(s.equals(ss)); // true