字符串的內容一旦發生了變化,那麼馬上會創建一個新 的對象。
注意: 字符串的內容不適宜頻繁修改,因爲一旦修改馬上就會創建一個新的對象。
如果需要頻繁修改字符串 的內容,建議使用字符串緩衝 類(StringBuffer)。
StringBuffer 其實就是一個存儲字符 的容器。
public class Demo1 {
public static void main(String[] args) {
String str1 = "hello";
String str2 = str1+" world";
System.out.println("str1與str2是同一個 對象嗎?"+(str1==str2));
}
}
運行結果:
str1與str2是同一個 對象嗎?false