1、String 是不可變的
String字符串一旦創建不可更改,如下:
public static void main(String[] args) {
String s = "hello";
System.out.println(s);//hello
tell(s);
System.out.println(s);//hello
s= s +"word";
System.out.println(s);//helloword
}
public static void tell(String s ){
s = "word";
System.out.println(s);//word
}
可以看出,定義字符串s爲hello後,在堆內存中爲“hello”的s分配一塊內存,調用tell函數後,又爲tell函數中的“word”新分配一塊內存,運行S+“word”時,又重新分配了一塊內存,調用tell函數後重新輸出s,s仍爲“hello”。
2.StringBuffer 是可變的。
public static void main(String[] args) {
StringBuffer s = new StringBuffer();
s.append("hello");
System.out.println(s.toString());//hello
tell(s);
System.out.println(s.toString());//helloword
}
public static void tell(StringBuffer s ){
s.append("word");
System.out.println(s.toString());//helloword
}
由上面的例子可以看出,StringBuffer是可變的。使用 StringBuffer 類時,每次都會對 StringBuffer 對象本身進行操作,而不是生成新的對象並改變對象引用。所以多數情況下推薦使用 StringBuffer ,特別是字符串對象經常改變的情況下。
3、StringBuilder
一個可變的字符序列。該類被設計用作 StringBuffer 的一個簡易替換,用在字符串緩衝區被單個線程使用的時候(這種情況很普遍)。如果可能,建議優先採用該類,因爲在大多數實現中,它比 StringBuffer 要快。但是將 StringBuilder 的實例用於多個線程是不安全的。